1060 Are They Equal (25point(s))
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
題目大意:
輸入一個整數 N,兩個小數 A、B,問將這兩個小數保存爲 N 位小數的科學計數法後,兩小數是否相等,並輸出用科學計數法表示後的數
設計思路:
重點在於確定係數的有效數字和指數
- 去除小數點前的前導 0 後
- 若小數點前有數字,指數爲正
- 則數字有幾個,對應指數就爲幾
- 保留有效位數
- 若小數點前無數字,指數爲負
- 則小數點後有幾個 0,對應指數就爲負幾
- 保留有效位數
- 若小數點前有數字,指數爲正
- 有效位數不足題目要求,後面補 0
這裏提供一些測試用例,
1 0 00.0
1 0.1 1.0
2 0.0 0.0010
4 00012.3 0.00123
注意:
- 指數爲 0 和 1 次方也要輸出
- 無需四捨五入
編譯器:C (gcc)
#include <stdio.h>
int main(void) {
int n;
char num[2][110] = {0};
char ch;
int i, flag, flag2, count, exp[2] = {0};
scanf("%d ", &n);
for (i = 0; i < 2; i++) {
flag = 0;
flag2 = 0;
count = 0;
exp[i] = 0;
while ((ch = getchar()) != ' ' && ch != '\n') {
if (flag == 0) {
if (ch == '.') {
flag = -1;
continue;
} else if (ch > '0') {
flag = 1;
}
}
if (flag == -1) {
if (ch != '0') {
flag2 = 1;
}
if (flag2 == 0) {
exp[i]--;
} else if (flag2 == 1 && count < n) {
num[i][count] = ch;
count++;
}
}
if (flag == 1) {
if (ch != '.') {
if (flag2 == 0) {
exp[i]++;
}
if (count < n) {
num[i][count] = ch;
count++;
}
} else {
flag2 = 1;
}
}
}
if (flag == -1 && flag2 == 0) {
exp[i] = 0;
}
while (count < n) {
num[i][count] = '0';
count++;
}
}
if (exp[0] == exp[1] && strcmp(num[0], num[1]) == 0) {
printf("YES 0.%s*10^%d", num[0], exp[0]);
} else {
printf("NO 0.%s*10^%d 0.%s*10^%d", num[0], exp[0], num[1], exp[1]);
}
return 0;
}