PAT (Advanced Level) Practice - 1060 Are They Equal(25 分)

题目链接:点击打开链接

题目大意:将两个 float 型数据使用科学计数法表示,并比较两者是否相同。

解题思路:主要比较【有效数字】和【指数】是否相同即可。要考虑所给输入数据的多种情况,比如 0 , 0.0,0.0123,05.032,00.020等这种比较特殊的情况。。

AC 代码

#include<bits/stdc++.h>
#include<cmath>

#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f
#define MOD 1000000007

using namespace std;

typedef long long ll;

string s1,s2,nums[2];
int n,es[2];

void fun(string s,int id)
{
    int len=s.length(), i=0, l, r;
    while(s[i]=='0') i++;
    l=i;

    if(s[i]=='.') // 0.#
    {
        i++;
        while(s[i]=='0') i++;
        r=i-1;
        es[id]=i==len?0:l-r; // 0.0 的情况
        l=i;
    }
    else // #.#
    {
        while(s[i]!='.' && i<len) i++;
        r=i;
        es[id]=r-l;
    }

    int cnt=0;
    for(int j=l;cnt<n;j++)
    {
        if(j>=len) nums[id].append(1,'0'), cnt++; // 不足末尾补 0
        if(isdigit(s[j]))
        {
            nums[id].append(1,s[j]);
            cnt++;
        }
    }
}

int main()
{
    while(cin>>n>>s1>>s2)
    {
        fun(s1,0); fun(s2,1);

        if(es[0]==es[1] && nums[0]==nums[1]) printf("YES 0.%s*10^%d\n",nums[0].c_str(),es[0]);
        else printf("NO 0.%s*10^%d 0.%s*10^%d\n",nums[0].c_str(),es[0],nums[1].c_str(),es[1]);
    }

    return 0;
}

/* 特殊样例

3 0.001234 1.234
3 0 0.0

*/

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/81780362