题目
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×105with 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
思路
找出小数点’.'出现的位置,记做dot;找出第一个有效数字(1-9)出现的位置,记做digit。由此可找出指数:
- 如果dot在digit之前,说明是0.XXX123 的形式,dot - digit + 1 即是指数
- 如果dot在digit之后,说明是0123.XXX的形式,dot - digit 即是指数
若dot未出现,则可将其视作出现在数字末尾;若digit未出现,说明此数是0,将其视作出现在dot处。
从digit后数N位有效数字即为底数,不足的话补0。
最后将底数和指数按要求拼接成字符串即可。
坑点
测试点6考察两个0的情况,参考下面测试用例:
5 0.00 0
YES 0.00000*10^0
之前测试点4也出了问题,是因为给底数添加有效位数字时把‘0’给过滤掉了,参考下面测试用例:
3 1024 1240
NO 0.102*10^4 0.124*10^4
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
int n;
cin >> n;
vector<string> s(2); //保存A、B
vector<string> d(2, "0."); //保存转换后的结果
for (int i=0; i<2; i++){
cin >> s[i];
int len = s[i].size();
int dot = 0; //小数点的位置
int digit = 0; //第一个有效位的位置
while (dot<len && s[i][dot]!='.'){
dot++;
}
while (digit<len && (s[i][digit]<'1' || s[i][digit]>'9')){
digit++;
}
if (digit==len){ //没有有效位,值为0
digit = dot;
}
int exp = dot<digit ? (dot-digit+1) : (dot-digit);
int count = 0; //有效位个数
for (int j=digit; j<len; j++){
if (s[i][j]>='0' && s[i][j]<='9'){
d[i] += s[i][j];
count++;
if (count==n){
break;
}
}
}
while (count < n){
d[i] += '0';
count++;
}
d[i] += "*10^";
d[i] += to_string(exp);
}
if (d[0]==d[1]){
cout << "YES " << d[0] << endl;
}
else{
cout << "NO " << d[0] << " " << d[1] << endl;
}
return 0;
}