Scientific Notation (20分)
单词:
- scientific notation:科学计数法 notation:符号,记号
- trailing:尾部的
- the fractional portion:小数部分
- the integer portion has exactly one digit, there is at least one digit in the fractional portion:
- 整数部分只有 1 位,小数部分至少有 1 位
总结:
- 数据范围:①数字存储≤9999 bytes,1个char变量=1 byte → 数字长度 ≤ 9999。②指数绝对值≤9999(可用int型变量)。
- 思路:输入部分为(小数部分)E(指数部分)。第一步定位E,再对(小数部分)和(指数部分)分情况讨论。
- 小数部分x:确定小数点位置。
- 指数部分e:
- ①e<0,小数点前移|e|位,0.0...0xxx,输出“0.”,再输出abs(e)-1个0。
- ②e>0,小数点后移e位,x...x.x...x,输出x中e个字符,在对应位置补小数点;
- x...x..0...0,若x输出完而仍需后移(e>0),无小数点,末尾需要补0。
注意:stoi()函数:string→int。
- 示例:stoi(str,i,n)代表将n进制的字符串str从str[i]开始的部分转化为十进制。
- ※字符串str中含非数字的字符,则只会识别从开头到第一个非法字符之前,如果第一个字符就是非法字符则会报错。
- ∴本题用字符E之后的子串,而不能写作int e = stoi( a,pos+1,10);这种。
代码:
//A1073 B1024
#include <iostream>
using namespace std;
#include <cstring>
int main(){
string a;
cin>> a;
int pos=0;
while( a[pos]!='E' )
pos++;
string x = a.substr(1,pos-1);//底数x 不含符号
int e = stoi( a.substr(pos+1) ); //指数e a.substr(i)从下标i到结尾
if( a[0]=='-' ) cout<<"-";
if(e<0){
cout<<"0.";
for(int i=e+1; i<0; i++){
cout <<"0";
}
cout<<x[0];
cout<<x.substr(2);
}else{
cout<<x[0];
//小数部分 从x[2]开始
for( int i=2; i<x.length(); i++){
if( e==0 ){
cout<<".";
cout<<x.substr(i);
break; //需要break跳出循环 否则会超时
}
//if( e==0 ) cout<<"."; 原来写法 测试点4超时
cout<<x[i];
e--;
}
while( e ){
cout<<0;
e--;
}
}
return 0;
}