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*10^5^ 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


题目大意:给定有效位数, 判断两个浮点数是否相同, 并且输出浮点表示
思路:找到第一个非0数字的位置a0,以及小数点的位置adot, 如果a0>adot,则指数expa=a0-adot, 否则expa=a0-adot+1。删除小数点,以及有效位之前的0; 根据有效数字增加0,或者截断数字
注意点:当数字是0的时候指数一定的0,不管小数点在什么位置。 还有就是除了数字相同,还要指数相同的两个数字才是相等的。 开始没有考虑指数是负数需要加1,导致有一个点不能通过
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int main(){
 5     int n, i;
 6     string a, b;
 7     cin>>n>>a>>b;
 8     int la=a.size(), lb=b.size(), adot=la, bdot=lb, a0=0, b0=0;
 9     for(i=0; i<la; i++) if(a[i]=='.'){adot=i; break;}
10     for(i=0; i<lb; i++) if(b[i]=='.'){bdot=i; break;}
11     for(i=0; i<la; i++) if(a[i]>='1'&&a[i]<='9'){a0=i; break;}
12     for(i=0; i<lb; i++) if(b[i]>='1'&&b[i]<='9'){b0=i; break;}
13     int expa=adot-a0, expb=bdot-b0;
14     a.erase(adot,1); b.erase(bdot, 1);
15     for(i=0; i<a.size(); i++) if(a[i]!='0'){a0=i; break;}
16     for(i=0; i<b.size(); i++) if(b[i]!='0'){b0=i; break;}
17     a.erase(0, a0); b.erase(0, b0);
18     la=a.size(); lb=b.size();
19     for(i=0; i<n-la; i++) a.append("0");
20     for(i=0; i<n-lb; i++) b.append("0");
21     a.erase(n); b.erase(n);
22     if(a[0]=='0') expa=0;
23     if(b[0]=='0') expb=0;
24     if(expa<0) expa++;
25     if(expb<0) expb++;
26     if(expa==expb && a==b) cout<<"YES 0."<<a<<"*10^"<<expa<<endl;
27     else cout<<"NO 0."<<a<<"*10^"<<expa<<" 0."<<b<<"*10^"<<expb<<endl;
28     return 0;
29 }

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9166027.html