PAT (Advanced Level) Practice A1060 Are They Equal (25 分)(C++) (甲级)(字符串string)(我认为统一处理的代码最具程序员的美感)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/86652010

原题链接1060 Are They Equal

我认为统一处理的代码最具程序员的美感!

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

int main()
{
    int N, pos1, pos2;
    string A, B;
    cin>>N>>A>>B;
    while(A.length() && A[0] == '0') A.erase(A.begin());//把前面多余的0去掉
    while(B.length() && B[0] == '0') B.erase(B.begin());
    pos1 = A.find(".");//查找小数点所在位置
    pos2 = B.find(".");
    if(pos1 == -1) pos1 = A.length();//无小数点则认为小数点在最后
    else A = A.substr(0, pos1) + A.substr(pos1+1, A.length());
    if(pos2 == -1) pos2 = B.length();
    else B = B.substr(0, pos1) + B.substr(pos2+1, B.length());
    if(pos1 == pos2){//小数点位置相同则考虑把小于1的小数的小数点之后的0清除掉
        while(A.length() && A[0] == '0') A.erase(A.begin()), pos1--;//并修改小数点位置
        while(B.length() && B[0] == '0') B.erase(B.begin()), pos2--;
    }
    if(!A.length()) pos1 = 0;//该数为0,则小数点位置认为0即可
    if(!B.length()) pos2 = 0;
    while(A.length() < N) A += "0";//不足有效位则补零
    while(B.length() < N) B += "0";
    if(pos1 == pos2 && A.substr(0, N) == B.substr(0, N)){//小数点位置相同且有效位部分相同则输出YES
        cout<<"YES 0."<<A.substr(0, N)<<"*10^"<<pos1;
    }
    else{//否则NO,并将两个都输出
        cout<<"NO 0."<<A.substr(0, N)<<"*10^"<<pos1;
        cout<<" 0."<<B.substr(0, N)<<"*10^"<<pos2;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/86652010