1060 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×105 with 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 10
100
, 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*10^3 0.128*10^3
分析:
此题考查科学计数法。
1.首先确定小数点的位置u和第一个非零元素的位置w(因为当数为小于0的小数时可能存在大量的前导0),当w等于字符串的长度说明字符串对应的浮点数是0(或者0.0000..00,即多个0),虽然对于0来说指数可以用任何数表示,但是当用科学计数法进行比较时会导致不同的0是不相等的,为避免此情况,将不同的0的指数统一设定为0,测试点6考查的是这个。
注:测试点往往是程序的边界条件,本题第一次提交时,测试点6没过,实则是在while循环结束后未处理若没找到非零元素该如何如何的情况,漏掉了边界条件。在编程时若遇到控制流的走向判断(e.g. if条件,for,while循环,)条件要完备,处理走向要完备~~~
#include<iostream>
using namespace std;
int n;
void f(string &s,int &u){
u=0;
int len=s.length();
while(u<len&&s[u]!='.') u++;
if(u==len){
int t=u;
if(s=="0") u=0;
for(int i=0;i<n-t;i++){
s.push_back('0');
}
}else{
int w=0;
while(w<len&&(s[w]=='0'||s[w]=='.')) w++;
if(w==len) w=u;
s.erase(u,1);
while(s[0]=='0') s.erase(0,1);
len=s.length();
for(int i=0;i<n-len;i++){
s.push_back('0');
}
if(u<w) u=u-w+1;
else u=u-w;
}
s="0."+s.substr(0,n);
}
int main(){
string s1,s2;
cin>>n>>s1>>s2;
int u1=0,u2=0;
f(s1,u1);
f(s2,u2);
if(u1==u2 && s1==s2){
cout<<"YES "<<s1<<"*10^"<<u1;
}else{
cout<<"NO "<<s1<<"*10^"<<u1<<" "<<s2<<"*10^"<<u2;
}
return 0;
}