【PAT】1060 Are They Equal (25)(25 分)

1060 Are They Equal (25)(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

 

科学计数法,注意以下几种情况:

  1.数字前有 0 的,比如:00056;0000.32 等,需先去除无效的0;

  2.指数 e 的正负计算,0.1 = 0.1*10^0;

  3.不同情况下有效位的计算,比如00056,0.00032;

  4.按题目要求输出有效位数,不足的后面补0;

 

C++代码如下:

 1 #include<iostream>
 2 #include<string>
 3 #include<iomanip>        
 4 using namespace std;
 5 
 6 
 7 void deal(string &s, int &e) {
 8     while (s.length() > 0 && s[0] == '0') s.erase(s.begin());
 9     int i;
10     if (s[0] == '.') {
11         s.erase(s.begin());
12         while (s.length()>0&&s[0] == '0') {
13             e--; 
14             s.erase(s.begin());
15         }
16         if (s.length() == 0) e = 0;
17     }
18     else {
19         for ( i = 0; i < s.length(); i++) {
20             if (s[i] != '.')    e++;                
21             else break;
22         }
23         if(i<s.length()) s.erase(s.begin() + i);
24     }
25 }
26 void signdigit(string &s,int n) {
27     while (s.length() < n) s += '0';
28     s.resize(n);
29 }
30 int main() {
31     string str1, str2;
32     int n,e1=0,e2=0;
33     cin >> n >> str1 >> str2;
34     deal(str1, e1);
35     deal(str2, e2);
36     signdigit(str1, n);
37     signdigit(str2, n);
38     if (str1 == str2 && e1 == e2)
39         cout << "YES 0." << str1 << "*10^" << e1 << endl;
40     else
41         cout << "NO 0." << str1 << "*10^" << e1 << " 0." << str2 << "*10^" << e2 << endl;
42     return 0;
43 }
posted on 2018-08-22 17:47  Pink.Pig  阅读(168)  评论(0编辑  收藏  举报