1060 Are They Equal——PAT甲级真题


1060 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*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 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.d1...dN*10^k" (d1>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

题目大意:让你用科学计数法表示两个数字,然后判断用科学计数法表示的两个数字是否相等,其中n为有效数字位数。

大致思路:

  1. 先排除前导0的影响,删除当前字符串的所有前导0,然后在判断当前字符串是>1 还是<1.
  2. 如果>1,设置一个指针K遍历当前字符串,直到找到小数点或者遍历到字符串的最后一位。然后删除小数点,同时在遍历的时候指数部分e也要不断增加
  3. 如果<1, 设置一个指针k遍历当前字符串,不断删除小数点后面的前导0,同时指数部分e不断-1.
  4. 上述过程处理完之后,在判断当前字符串的长度和n的大小,如果

代码:

#include 

using namespace std;

int n;

string changeNum(string str, int& e) {
    int k = 0;  //str的下标
    while(str.length() > 0 && str[0] == '0')
        str.erase(str.begin()); //先去掉前导0
    //如果是小数
    if (str[0] == '.') {
        str.erase(str.begin());
        //去掉非0位前面的所有0
        while(str.length() > 0 && str[0] == '0') {
            str.erase(str.begin());
            e--;    //小数,指数依次递减
        }
    } 
    //如果是整数
    else {
        while(k < str.length() && str[k] != '.') {
            k++;
            e++;
        }
        if (k < str.length()) str.erase(str.begin() + k);
    }
   
    //说明这个数为0
    if (str.length() == 0)  e = 0;  //指数为0
    int num = 0; k = 0;
    string ans = "";
    while(num < n) {
        if (k < str.length()) ans += str[k++];
        else ans += '0';    //如果超过表示范围后面要补0
        num++;
    }
    return ans;
}

int main() {
    string str1, str2;
    cin >> n >> str1 >> str2;
    int e1 = 0, e2 = 0;
    string ans1 = changeNum(str1, e1), ans2 = changeNum(str2, e2);
    if (ans1 == ans2 && e1 == e2) cout << "YES 0." << ans1 << "*10^" << e1 << endl;
    else cout << "NO 0." << ans1 << "*10^" << e1 << " " << "0." << ans2 << "*10^" << e2 << endl; 
    return 0;
}