个人学习记录,代码难免不尽人意。
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
#include<cstdio>
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
string substr(string str,int i,int j){
string s;
for(int k=i;k<j;k++){
s+=str[k];
}
return s;
}
void change(string s1,int s2,char c){
bool flag;
if(s1[0]=='+'){
flag=true;
}else flag=false;
s1.erase(s1.begin(),s1.begin()+1);
int index;
for(int i=0;i<s1.size();i++){
if(s1[i]=='.'){
index=i;
break;
}
}
if(c=='+'){
int digitafterpoint=s1.size()-1-index;
if(digitafterpoint>s2){
string temp1=substr(s1,0,index+s2+1);
temp1=temp1+'.';
string temp2=substr(s1,index+s2+1,s1.size());
temp1=temp1+temp2;
temp1.erase(temp1.begin()+index,temp1.begin()+index+1);
if(flag)
cout << temp1;
else
cout << '-' <<temp1;
}
else if(digitafterpoint==s2){
s1.erase(s1.begin()+index,s1.begin()+index+1);
if(flag)
cout << s1;
else
cout << '-' <<s1;
}
else{
int numberofz=s2-digitafterpoint;
s1.erase(s1.begin()+index,s1.begin()+index+1);
for(int i=0;i<numberofz;i++){
s1+='0';
}
if(flag)
cout << s1;
else
cout << '-' <<s1;
}
}
else{
int digitbeforepoint=index;
if(s2<digitbeforepoint){
s1.erase(s1.begin()+index,s1.begin()+index+1);
string temp1=substr(s1,0,digitbeforepoint-s2);
temp1+='.';
string temp2=substr(s1,digitbeforepoint-s2,s1.size());
temp1=temp1+temp2;
if(flag)
cout << temp1;
else
cout << '-' <<temp1;
}
else{
s1.erase(s1.begin()+index,s1.begin()+index+1);
for(int i=0;i<=s2-digitbeforepoint;i++){
if(i==s2-digitbeforepoint)s1='.'+s1;
s1='0'+s1;
}
if(flag)
cout << s1;
else
cout << '-' <<s1;
}
}
}
int main(){
string s1;
int s2;
getline(cin,s1,'E');
char c=getchar();
cin >> s2;
change(s1,s2,c);
}
这道题一开始我想将字符串先转换成double来做,后来发现有几个地方不能实现:①题目要求输出原数据会被double省略的0(参考input1)②如果尾数太大double在输出的时候会自动转换成科学计数法,这样也不行。
所以还是只能用string来进行模拟。
用string也比较简单,首先根据小数点的移动方向分为向前和向后两种情况,对应了E后面的数小于0和大于0。然后分类讨论即可,详情请看代码。
还需要注意的是,小数点向前和向后二种情况不能简单的复用,因为小数点向后移动时,如果移动位数正好等于原小数点后数字个数,则不需要再输出小数点,而向前移动时无论怎么样都要有小数点!