Description
科学计数法是将一个数字表示成 a×10的n次方的形式.其中1≤|a|<10,n为整数。
我们给你一个数x, 请把它用科学计数法表示出来,并保留 k 位有效数字。
有效数字是指在一个数中,从该数的第一个非零数字起,直到末尾数字止的数字称为有效数字,如0.618的有效数字有三个,分别是6,1,8。(不用考虑四舍五入)
Input
多组测试数据(组数<=100)。
每组输入形如:
x k
0< x< 10^120, 0< k<20, 注意读入的数字可能会有前置0。
Output
请输出对应的科学计数后的数。
Sample Input
1030 3
1000 2
0.0032 3
Sample Output
1.03e3
1.0e3
3.20e-3
比赛的时候WA了好多发,考虑各种情况,各种判断,emmm大概是最麻烦的方法了
不考虑四舍五入,可用字符串输入
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
string st;
int k;
while(cin>>st>>k)//开始时用getline()会把k当作字符读取
{
bool flag=false;//立下一个flag
int len=st.size();
int firstpos=0;//开始位置
int pointpos=0;//小数点位置
for(int i=0;i<len;i++)//循环遍历
{
if(st[i]=='.')//若读取到小数点,记录小数点的位置
{
pointpos=i;//是否为小数
}
else if(st[i]!='0'&&flag==false)//flag用于判断是否第一次读取非零字符
{
firstpos=i;
flag=true;
}
}
int tmp=firstpos;//存储第一个非零字符的位置
cout<<st[firstpos];//输出第一位,即小数点前一位
if(k!=1)
{
cout<<".";//有效数字为1不必输出小数点
}
for(int i=1;i<k;i++)//k为有效数字数,因为已经输出一位有效数字,故循环次数只需k-1次
{
if(st[firstpos+1]=='.')//若读取小数点,跳过
{
firstpos++;
}
if(firstpos+1>len-1)//超出字符串长度用0代替
{
cout<<0;
}
else if(st[firstpos+1]!='.')//输出不是小数点的字符
{
cout<<st[firstpos+1];
}
firstpos++;
}
if(pointpos==0)//不存在小数点
{
cout<<"e"<<len-1-tmp<<endl;
}
else if(pointpos<tmp)//为小数
{
cout<<"e"<<pointpos-tmp<<endl;
}
else if(pointpos>tmp)//小数在后
{
cout<<"e"<<pointpos-tmp-1<<endl;
}
}
return 0;
}