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,因此本体部分是从小数点后第一个非零位开始的部分(不足 n 位则补 0),指数则是小数点与该非零位之间的 0 的个数的相反数。
- 整数部分不为 0:本体部分是去掉小数点后的第一个非零位开始的 n 个字符(不足 n 位则补 0),指数则是小数点或最后一位(如没有小数点)之前的非零位数。
不管是哪种情况,如果有小数点,都需要把小数点去掉,这样才能输出正确的本体。
注意点
- 此题有一个陷阱:数据有可能出现前导 0,应该先去除前导零,然后再根据首位是否为小数点来判断是情况 1,还是情况2。
- 去除前导零后,若字符串长度为 0,则代表该数为 0,应将指数值为 0,否则有可能因小数点后全为 0 的情况,指数变为负数。
#include <iostream>
#include <string>
using namespace std;
int n;
string a, b;
void chopping(string &str, int &e) {
while (str[0] == '0' && str.length() > 0) {
str.erase(0, 1);
}
if (str[0] == '.') {
str.erase(0, 1);
while (str[0] == '0' && str.length() > 0) {
str.erase(0, 1);
e--;
}
} else {
if (str.find('.') == string::npos) {
e = str.length();
} else {
e = str.find('.');
str.erase(str.find('.'), 1);
}
}
int len = str.length();
if (len == 0) {
e = 0;
}
if (str.length() < n) {
for (int i = 0; i < n - len; i++) {
str.append("0");
}
} else if (len > n) {
str = str.substr(0, n);
}
}
int main() {
cin >> n >> a >> b;
int e1 = 0, e2 = 0;
chopping(a, e1);
chopping(b, e2);
if (a == b && e1 == e2) {
printf("YES");
cout << " 0." << a << "*10^" << e1;
} else {
printf("NO");
cout << " 0." << a << "*10^" << e1;
cout << " 0." << b << "*10^" << e2;
}
return 0;
}