- 题目:
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.12010^3 0.12810^3
-
题目大意
将两个数改写为科学记数法形式,然后判断两个数是否相等。 -
分析
可能会出现两种情况
1.0.aaaaaa //小数
2 aaaaa.bbbb //整数
对于输出的数,可能会出先前导0,
1.首先去除前导0
2.然后判断第一位为小数点还是其他书,若为小数点,则此数为小数,否则为整数
3.对于小数,先将小数点删除,在去除前面所有0,直到第一个非0的字符出现或者已到达末尾;对于整数,查找小数点的位置,并将小数点删除,并更新指数的值
4.返回指定的前缀字符串,若不够,则补0 -
代码实现
#include <string>
#include <iostream>
using namespace std;
int n;
string del(string a, int& e){
int index = 0;
while(a.length() > 0 && a[0] == '0'){ //去除前导0
a.erase(a.begin());
}
if(a[0] == '.') { //说明为小数{
a.erase(a.begin()); //去除小数点
while(a.length() > 0 && a[0] == '0'){
a.erase(a.begin());
e--; //没减去一个0,指数减一
}
} else { //否则为正数
while(index < a.length() && a[index] != '.'){
index++;
e++;
}
if( index < a.length())
a.erase(a.begin() + index);
}
if(a.length() == 0)
e = 0;
string temp;
index = 0;
int num = 0;
while(num < n){
if(index < a.length())
temp += a[index++];
else
temp += '0';
num++;
}
return temp;
}
int main()
{
int e1 = 0, e2 = 0;
string st1, st2;
cin >> n >> st1 >>st2;
st1 = del(st1, e1);
st2 = del(st2, e2);
if(st1 == st2 && e1 == e2){
cout << "YES" << " ";
cout << "0." << st1 << "*10^"<< e1;
} else {
cout <<"NO" << " ";
cout << "0."<< st1 << "*10^"<< e1 << " ";
cout << "0."<< st2 << "*10^"<< e2;
}
return 0;
}