PAT (Advanced Level) Practice
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
个人代码:
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int n, indexA, indexB; //记录标准输出的指数
string strA, strB;
int indexLen (string &str) {
int lens = 0;
string::iterator it = str.begin();
//去除前导0
while (*it == '0') {
if (str.length() != 1) {
str.erase(it);
} else { //0
return 0;
}
}
if (*it == '.') { //0.---
str.erase(it); //去除小数点
if (*it != '0') {
return 0; //0.k(k!=0)
} else {
int i = 0;
//去除0.类的小数点后面的连续0
while (str.length() != 1) {
if (*it == '0') {
i++;
str.erase(it);
} else {
break;
}
}
if (*it == '0') {
return 0; //0.0
} else {
return -i; //0.0k(k!=0)
}
}
} else { //k或者k.---(k!=0)
if (str.find(".") == -1) {
return str.length(); //k
} else {
int flo = str.find(".");
str.erase(it + str.find(".") );
return flo; //k.---
}
}
}
void print(string str) {
int len = str.length();
for (int i = 0; i < n; i++) {
if (i < len) {
printf("%c", *(str.begin() + i));
} else {
printf("0");
}
}
}
int main () {
cin >> n >> strA >> strB;
//确定指数
indexA = indexLen(strA);
indexB = indexLen(strB);
bool flag = true; //判断YESorNO
if (indexA != indexB) {
flag = false;
} else {
for (int i = 0; i < n; i++) {
if (*(i + strA.begin()) != *(i + strB.begin())) {
flag = false;
break;
}
}
}
if (flag) { //输出
printf("YES 0.");
print(strA);
printf("*10^%d", indexA);
} else {
printf("NO 0.");
print(strA);
printf("*10^%d 0.", indexA);
print(strB);
printf("*10^%d", indexB);
}
return 0;
}
思路提示:
本题的构思并不复杂,但是坑很多,特别是0开头的数据。由于题目的提示不是很多,所以需要自己去尝试。
建议将一个数分为这几类:0、0.0、0.0k、k、k.k,这样易于理解。其中0代表的是一连串的0,k代表的是不为0的数。
可以看出由0开头的数据最为复杂且容易出错,因此需要仔细一点!
建议是先得出指数,然后把连续的0和小数点处理掉。
再最后打印时,如果有数位不够的情况需要补0.
另外,这题代码的很多部分都可以复用,这样可以减少代码量,让代码更简洁。
测试用例:
3 12300 12358.9
3 120 128
5 0.00001 0.00001
1 0.001 0.2000
2 005.06 0.230
1 00.020 0