PAT--1060. Are They Equal(字符串处理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xushao_Movens/article/details/53543984

Description

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.120*10^3 0.128*10^3

题解

把两个数表示为有N位有效数字的科学记数法形式,比较是否相等。
关键在于:指数和有效数字。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace std;

int n;
string a, b;

int main(){
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif // ONLINE_JUDGE
    cin >> n >> a >> b;
    int pos;
    // 小数点
    int dota = (((pos = a.find('.')) != string::npos) ? pos : a.length());
    int dotb = (((pos = b.find('.')) != string::npos) ? pos : b.length());

    // 去除前导0  e.g. 0.123
    // 从有效数位开始
    int p = 0, q = 0;
    while(a[p] == '0' || a[p] == '.') p++;
    while(b[q] == '0' || b[q] == '.') q++;

    // 指数,当然可以是负的
    int exp_a = 0, exp_b = 0;
    if(dota >= p) exp_a = dota - p;
    else exp_a = dota - p + 1;
    if(dotb >= q) exp_b = dotb - q;
    else exp_b = dotb - q + 1;

    // 处理为0的情况, 000, 指数为0
    if(p == a.length()) exp_a = 0;
    if(q == b.length()) exp_b = 0;

    // 如果n大于位数,补0
    // e.g. 5 0.123 --> 0.12300*10^-1
    string A, B;
    int indexA = 0, indexB = 0;
    while(indexA < n){
        if(a[p] != '.' && p < a.length()) A += a[p], indexA++;
        else if(p >= a.length()) A += '0', indexA++;
        p++;
    }
    while(indexB < n){
        if(b[q] != '.' && q < b.length()) B += b[q], indexB++;
        else if(q >= b.length()) B += '0', indexB++;
        q++;
    }
    // 指数相等, 有效数字部分相等
    if(A == B && exp_a == exp_b){
        printf("YES 0.%s*10^%d\n", A.c_str(), exp_a);
    }else{
        printf("NO 0.%s*10^%d 0.%s*10^%d\n", A.c_str(), exp_a, B.c_str(), exp_b);
    }

    return 0;
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页