Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [±][1-9]”.”[0-9]+E[±][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent’s signs are always provided even when they are positive.
Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.
Input Specification:
Each input file contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent’s absolute value is no more than 9999.
Output Specification:
For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros,
Sample Input 1:
+1.23400E-03
Sample Output 1:
0.00123400
Sample Input 2:
-1.2E+10
Sample Output 2:
-12000000000
题目大意
给出科学计数法,要求输出普通数字,并保持它的精度(小数末尾的0不要扔)。
思路
将科学记数法存到一个字符数组中,记录指数符号E的位置,遍历计算出指数。如果指数是负数,那么输出0.000xxxxxx的形式,就考虑补几个前导0,然后输出原来的数字(忽略原来的".")。如果指数是正数就考虑小数点往右移动几位,注意小数点不能在最后一位。
补充输入输出
第一组
输入:+1.234000E+03
输出:1234.000
第二组
输入:+1.234E+03
输出:1234
代码
#include <iostream>
#include <cstdio>
#include <cstring>
int main() {
char str[10010], symbol;
int pos;
scanf("%s", str);
if(str[0] == '-') putchar('-');
int i = 0;
while (str[i] != 'E') i++;
// 记录指数符号E的位置。
pos = i;
// E的右边是指数的符号
symbol = str[++i];
//再向右移一位才是指数的最高位
i++;
// 读取指数
int exp = 0;
while (str[i] != '\0') {
if(exp == 0 && str[i] == '0'){
i++;
continue;
}
exp = exp * 10 + (str[i] - '0');
i++;
}
if(symbol == '-') exp = -exp;
// 指数是负数的情况
if(exp < 0){
printf("0.");
// 补0,exp是-n的时候补n-1个0
for(int j = - exp - 1; j > 0; j--) putchar('0');
// 输出数字,忽略原来的"."
for(int j = 1; j < pos; j++){
if(str[j] == '.') continue;
putchar(str[j]);
}
}else{
// 输出数字,忽略原来的"."
for(int j = 1; j < pos; j++){
if(str[j] == '.') continue;
// 移动小数点,记住小数点不能在最后一位
if(j == exp + 3 && pos - 3 != exp) putchar('.');
putchar(str[j]);
}
// 补上后面的0
for(int j = pos - 3; j < exp; j++){
putchar('0');
}
}
return 0;
}