1073 Scientific Notation (20 point(s))
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 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
题目大意
将用科学计数法计数的数字转化为普通数字,题目保证输入数据满足[±][1-9].[0-9]+E[±][0-9]格式
解题思路
首先找到小数点和‘E’的位置,即把整数部分和小数部分及指数部分分开,如果指数小于0,则在整数左边补0,否则再判断指数与小数位数的大小:若指数大于小数长度,则在后面补差值个0,否则在小数部分找到合适位置插入小数点
代码
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str, res, inte, deci, expo;
cin >> str;
int i, j;
for (i = 0; i < str.size() && str[i] != '.'; ++i);//找到小数点的位置
inte = str.substr(1, i - 1);//存储整数
for (j = i; j < str.size() && str[j] != 'E'; ++j);
deci = str.substr(i + 1, j - i - 1);//存储小数
expo = str.substr(j + 1);//存储指数
int exp = stoi(expo);
//cout << "exp = " << exp << endl;
//cout << "deci = " << deci << endl;
if (str[0] == '-')
res = "-";
if (exp < 0) {//如果指数为负
res += string(-exp, '0') + inte + deci;
if (str[0] == '-') {
res.insert(2, ".");//如果为负,在第二个位置插入小数点
}
else res.insert(1, ".");//否则在第一个位置插入小数点
}
/*else if (exp == 0) {
res += inte + "." + deci;
}*/
else {
if (exp > deci.size()) {
res += inte + deci + string(exp - deci.size(), '0');//补0
}
else if (exp < deci.size()) {
deci.insert(exp, ".");
//cout << deci << endl;
res += inte + deci;
}
else res += inte + deci;//指数与小数位数相等,直接拼接
}
cout << res << endl;
return 0;
}