1073 Scientific Notation (20分)
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]+,这里提示一下+ 这个符号,在正则表达式中,表示前一个字符的出现次数为>=1。现在要你将这个表达式以它规定的规则输出。
输出规则:
1)表达式的第一个字符判断该数为正数或负数,若为负数,则输出'-'号
2)字母E后接的是正符号 或 负符号,正号表示将这个数扩大,负号表示将这个数缩小
3)字母E后面接的数字表示扩大或缩小多少,小数点往前移多少位,往后移多少位。
输入:字符串
输出:按规则输出
解题思路:
表达式中'.'和'E'是固定给出的,可以根据这两个字符将字符串切分。将数字部分提取出来,稍后进行字符串拼接。例如将小数点前的数字记为s1,小数点到字母E之间的数字记为s2,字母E后面的数字记为s3,且将s3转化为整数k,以便将数字放大或缩小。
可以将放大和缩小分开来求。1、若k=0,就表示不需要将数据放大或缩小,直接将s1和s2进行拼接,注意s1和s2之间还需加上个小数点;2、将数据缩小其实就是考虑怎么在数据前补0的问题,讨论要不要补0,或要补多少。直接用k减去s1的长度就能求出该在0.后追加几个0了;3、将数据放大则考虑在s2后补多少个0,这要分两部分讨论,1)当扩大倍数小于s2字符串长度(数据本身的小数点位数)时,这种情况下不用补0,需要把小数点放到正确的位置,再将字符串进行拼接就行。2)当扩大倍数大于s2字符串长度时,需要补0,补多少个0,直接k减去s2字符串长度即可。
注意:测试点4,就是讨论当扩大倍数小于s2字符串长度(数据本身的小数点位数)时的情况。
附加测试点4测试数据:
输入:-1.123456E+03,输出-1123.456
#include<bits/stdc++.h>
using namespace std;
int get_num(string s){
int ans = 0;
for(int i=0; i<s.size(); i++){
ans = ans*10 + s[i]-'0';
}
return ans;
}
int main()
{
string s, str;
cin >> s;
if(s[0]=='-') cout << '-';
str = s.substr(1);
string s1="", s2="", s3="";
int g1=0, g2=0;
g1 = str.find('.');
g2 = str.find('E');
s1 = str.substr(0,g1);
s2 = str.substr(g1+1,g2-g1-1);
s3 = str.substr(g2+2);
int k = get_num(s3);
if(k==0){
cout << s1 + '.' + s2 << endl;
return 0;
}
string ans = "";
if(str[g2+1]=='-'){//前面追加
ans = "0.";
k-=s1.size();
while(k){
ans += '0';
k--;
}
ans = ans + s1 + s2;
}
else{//后面追加
int l = s2.size();
if(k-l<0){
ans += s1;
ans += s2.substr(0,k);
ans += '.';
ans += s2.substr(k);
}
else{
k-=s2.size();
ans = ans + s1 + s2;
while(k){
ans += '0';
k--;
}
}
}
cout << ans << endl;
return 0;
}