【PAT A1060】Are They Equal

【PAT A1060】Are They Equal
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 10100, 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]*10k (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.12010^3 0.12810^3
结尾无空行

代码:

#include <iostream>
#include <string>
using namespace std;
int n;    //有效位

string func(string s,int &e){
    int k = 0;
    while(int(s.length()) > 0 && s[0] == '0'){
        s.erase(s.begin());    //去掉前导的0
    }
    if(s[0] == '.'){           //去掉前导0后是小数点,说明这个数是小数
        s.erase(s.begin());
       while(int(s.length()) > 0 && s[0] == '0'){
           s.erase(s.begin());    //去掉小数点后不是零位置前的所有零
           e--;
       }
    }else{                     //去掉前导零后不是小数点,则找到后面的小数点删除
        while(k < int(s.length()) && s[k] != '.'){
            k++;
            e++;               //只要没遇到小数点就让指数e加一
        }
        if(k < int(s.length())){    //while结束后k < s.length(),说明遇到小数点
            s.erase(s.begin() + k);    //删除小数点
        }
        if(int(s.length()) == 0){
            e = 0;             //如果去除前导零后s的长度变为0,那么说明这个数就是0
        }
    }
    int num = 0;
    k = 0;
    string res;
    while(num < n){
        if(k < int(s.length()))
            res += s[k++];
        else
            res += '0';
        num++;            //精度加1
    }
    return res;
}

int main(){
    string s1,s2,s3,s4;
    cin >> n >> s1 >> s2;
    int e1 = 0,e2 = 0;
    s3 = func(s1,e1);
    s4 = func(s2,e2);
    if(s3 == s4 && e1 == e2){
        cout << "YES 0." << s3 << "*10^"<< e1 << endl;
    }else{
        cout << "NO 0." << s3 << "*10^" << e1 << " 0." << s4 << "*10^" << e2 << endl; 
    }
    return 0;
 }

提交结果截图:

问题:
1.结果出现一个答案错误,但不清楚其测试用例是什么?
2.warning: comparison between signed and unsigned integer expressions [-wsign-compare]
避免使用无符号数,其中使用了s.length(),返回的值应该是一个unsigned int,所以导致出现这个错误,因此在使用其进行比较的时候,需改为int(s.length())。
3.我不知道为什么这个markdown格式中只有105显示不成功!??

原文地址:https://www.cnblogs.com/techgy/p/15088085.html