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
分析:
此題考查科學計數(shù)法。
1.首先確定小數(shù)點的位置u和第一個非零元素的位置w(因為當數(shù)為小于0的小數(shù)時可能存在大量的前導0),當w等于字符串的長度說明字符串對應的浮點數(shù)是0(或者0.0000..00,即多個0),雖然對于0來說指數(shù)可以用任何數(shù)表示,但是當用科學計數(shù)法進行比較時會導致不同的0是不相等的,為避免此情況,將不同的0的指數(shù)統(tǒng)一設定為0,測試點6考查的是這個。
注:測試點往往是程序的邊界條件,本題第一次提交時,測試點6沒過,實則是在while循環(huán)結(jié)束后未處理若沒找到非零元素該如何如何的情況,漏掉了邊界條件。在編程時若遇到控制流的走向判斷(e.g. if條件,for,while循環(huán),)條件要完備,處理走向要完備~~~
#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;
}