1060 Are They Equal (25 分)
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.d[1]...d[N]*10^k
(d[1]
>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
不如分类讨论 多复制点代码而已 思路简单点 不怎么耗费时间 否则没有好的测试用例+打断点 很难调好
坑点:题目没有说清楚 开头可以有好多个0 值为0时指数为0
string.erase(m,1);删除下标为m的元素千万不能忘记",1"限定个数 这不是set 否则m后面的全部被删除了
s.substr() 是错的 必须赋值回给s即 s=s.substr()
比较难过的测试用例:
3 0.000 0
4 123.5678 123.5
5 0010.013 10.012
4 00100.000000012 100.000000013
4 0000.000000123 0.0000001230
3 0.0520 0.0521
#include<iostream>
#include<string>
using namespace std;
int n;
string a, b;
string ZERO() {//值为0时的返回值
string ans = "0.";
for (int i = 0;i<n;i++) ans = ans + "0";
ans = ans + "*10^0";//肯定是0次 不然肯定会特殊说明的
return ans;
}
//分类讨论还简单些
string stdard(string s) { //00123.567
//预处理 去掉前导0 小数点要留下 一步一步简化处理
int T = s.find_first_not_of("0");
if (T == string::npos) return ZERO();
else s=s.substr(T);//去掉开头的0 剩下的只有 .7895 .056 78955 789.55
int m = s.find('.');//小数点位置
int k = s.find_first_not_of(".0");//第一个有效数字下标位置
if (k == -1) return ZERO();
int p;//数量级
if (m == -1) p = s.length();//整数 12345 12345
else if (m>k) {//整数+小数 12345.0456 12345.0456
p = m - k;
s.erase(m,1);//q去掉小数点 ",1"千万别忘了 这不是set
}
else {//纯小数 .0046
p = -(k - m - 1);
s = s.substr(k);//开头的.0肯定要去掉 别忘记赋值给s
}
string d = s.substr(0, n);
while (d.length()<n) d = d + "0";//不够n位 末尾添0
char sign[3];sprintf(sign, "%d", p);
return "0." + d + "*10^" + sign;
}
int main() {
//freopen("in.txt", "r", stdin);
cin >> n >> a >> b;
a = stdard(a);b = stdard(b);
if (a == b) cout << "YES " << a;
else cout << "NO " << a << " " << b;
return 0;
}
来源:CSDN
作者:树叶子_
链接:https://blog.csdn.net/hza419763578/article/details/100173816