Are They Equal (25 分)
If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123×10 5with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.
Input Specification:
Each input file contains one test case which gives three numbers N, A and B, where N (<100) is the number of significant digits, and A and B are the two float numbers to be compared. Each float number is non-negative, no greater than 10100, and that its total digit number is less than 100.
Output Specification:
For each test case, print in a line YES if the two numbers are treated equal, and then the number in the standard form 0.d[1]…d[N]*10^k (d[1]>0 unless the number is 0); or NO if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.
Note: Simple chopping is assumed without rounding.
Sample Input 1:
3 12300 12358.9
Sample Output 1:
YES 0.123*10^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.120* 103 0.128*103
思路
分两种情况讨论:
1.xxx.yyy
2.0.xxx
首先需要知道两数的指数以及有效位数截断后的数,如果这两个都相等则两数相等。
首先去除前导0,接着判断下一位是否为小数点,如果是则说明这个数小于0,应再去除小数点后到有效位数之前的0,而指数绝对值就为这段0的个数;
如果否则说明这个数大于0,应遍历直到找到小数点,指数为从头到小数点之间的数的个数,并去掉小数点(没有可以省略)。
经过这一步已经求出来指数大小了,我们需要对剩余的字符串做截断处理:
如果小于有效位数,则在字符串首添加0;如果大于有效位数,则截取前有效位即可。
最后按照格式输出结果。
#include<bits/stdc++.h>
using namespace std;
int n;
string tackle(string str,int &e){
while(str.size()>0&&str[0]=='0'){
str.erase(str.begin());
}
if(str[0]=='.'){
str.erase(str.begin());
while(str.size()>0&&str[0]=='0'){
str.erase(str.begin());
e--;
}
}
else{
for(int i=0;i<str.size();i++){
if(str[i]=='.'){
str.erase(str.begin()+i);
break;
}
else{
e++;
}
}
}
if(str.size()==0) e=0;
while(str.size()<n){
str.insert(str.begin(),'0');
}
if(str.size()>n){
str.erase(str.begin()+n,str.end());
}
return str;
}
int main(){
cin>>n;
string s1,s2,x,y;
cin>>s1>>s2;
int e1=0,e2=0;
x=tackle(s1,e1);
y=tackle(s2,e2);
//cout<<x<<' '<<y<<endl;
if(x==y&&e1==e2){
printf("YES 0.%s*10^%d",x.c_str(),e1);
}else{
printf("NO 0.%s*10^%d 0.%s*10^%d",x.c_str(),e1,y.c_str(),e2);
}
return 0;
}