A1060
Description:
如果一个机器只能存储三位有效数字,那么浮点数12300和12358.9将被存为0.123x10^5,剩余的部分被简单截断了。现在给出一个及其的有效数字和两个浮点数,请你告诉他们在这个机器上是否相同。
Input:
- 每个输入一个样例;
- 首行给出三个数字:有效数字位数N<100,以及将要被比较的浮点数AB,每个浮点数都是非负的数字,不超过10的100次方,并且数字的总位数小于100。
Output:
- 若两科学计数法相同,则输出YES 及科学计数法,否则输出NO及两数字分别的科学计数法
算法描述:
- 自己模拟了一下,错了两组,思路是遍历查找出首个非零数字以及小数点所在位置,然后就可以计算出幂次e,有效数字则是从首个非零数字开始,向后拼接N位,如果超出输入数字位数,则补0
- 自己的方法涉及到很多下标运算,极易导致错误,看了晴神的解析,感觉很务实,代码是参考晴神的:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
int n;
string deal(string num){
int k = 0, e = 0;
//处理前导零
while(num.length() > 0 && num[0] == '0') num.erase(num.begin());
if(num[0] == '.'){ //前导零去除完毕后,首位是0,则为纯小数
num.erase(num.begin());
while(num.length()>0 && num[0] == '0'){
num.erase(num.begin());
e--;
}
}else{ //否则整数部分存在非零常数
while(k < num.length() && num[k] != '.') k++, e++;
if(k < num.length()) num.erase(num.begin() + k);
}
if(num.length() == 0) e = 0;
int in = 0;
k = 0;
string ans;
ans += "0.";
while(in < n){ //in控制有效数字位数,k控制不要超过原数最大长度
if(k < num.length()) ans += num[k++];
else ans += "0";
in++;
}
ans += "*10^"+to_string(e);
return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
string n1, n2;
cin>>n>>n1>>n2;
n1 = deal(n1);
n2 = deal(n2);
if(n1 == n2)
cout<<"YES "<<n1<<endl;
else
cout<<"NO "<<n1<<" "<<n2<<endl;
return 0;
}