【算法笔记】A1060 Are They Equal

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 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 (<) 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 1, 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

题意

  比较两个数的科学计数法是否相同,相同输出YES,否则输出NO。本题不需要考虑四舍五入。

思路

  把接收到的两个数删除掉前导的0。然后分为两种情况:一种是.00XXXX形式;另一种是XXXX.XXXX形式。

  如果是.00XXXX形式,删除小数点和小数点后面的0,直到碰到不为0的数,每删一个0,指数减1。

  如果是XXXX.XXXX形式,遍历字符串直到碰到小数点,把小数点删除。每遍历一个数,指数加1。

  最后比较改变后的字符串和指数,输出结果。注意输入 3 000.0 0 时输出 YES 0.000*10^0 

code:

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 string num1, num2;
 4 int n;
 5 static string turn(string a, int &e){//e前面加&,值才会被修改
 6     string result="0.";
 7     while(a.size()>0&&a[0]=='0'){//删除前导0
 8         a.erase(a.begin());
 9     }
10     if(a[0]=='.'){//0.XXXXXX形式
11         a.erase(a.begin());
12         while(a.size()>0 && a[0]=='0'){
13             a.erase(a.begin());
14             e--;
15         }
16     }else{//XXXX.XXXX形式
17         int k = 0;
18         while(k < a.size() && a[k]!='.'){
19             e++;
20             k++;
21         }
22         if(k<a.size()) a.erase(a.begin()+k);
23     }
24     if(a.size()==0) e = 0;//删除0和小数点后长度为0
25     int num = 0, k = 0;
26     while(num < n){
27         if(k < a.size()) result += a[k++];
28         else result += '0';
29         num++;
30     }
31     return result;    
32 }
33 int main(){
34     int e1 = 0, e2 = 0;
35     cin>>n>>num1>>num2;
36     string s1 = turn(num1,e1);
37     string s2 = turn(num2,e2);
38     if(s1 == s2 && e1 == e2)
39         cout<<"YES "<<s1<<"*10^"<<e1;
40     else 
41         cout<<"NO "<<s1<<"*10^"<<e1<<" "<<s2<<"*10^"<<e2;
42     return 0;
43 }

 

posted @ 2019-04-18 11:42  Resfeber  阅读(165)  评论(0编辑  收藏  举报