标题1024 科学计数法
这个题目分支判断较多。
**- 主要思路是将数值部分和幂次部分分别处理。
- 幂次部分的符号不同处理的方式不同。
- 正数幂次小于数值的位数的时候还需要考虑小数点的位置。
-**
代码想少用几个变量,所以可读性不太好。用注释尽量标识了,请见谅。
#include<iostream>
using namespace std;
int main() {
char read;
char data[10000];
bool token = true;
int idx = 0;
char expsign;
int expnumber = 0;
while ((read = getchar()) != '\n') {
if (read == 'E') {
token = false;
continue;
}//读取Exp的数字和符号
if (token)
data[idx++] = read;//读取数字部分
else {
if (read == '+' || read == '-')
expsign = read;
else
expnumber = expnumber * 10 + (int) read - '0';
}//读取指数部分
}//读入所有的字符串
if (data[0] == '-')
cout << data[0];//取出第一个符号并判断是否负号输出
if (expsign == '-')//负数指数小数部分输出
{
cout << '0' << '.';
for (int k = 0; k < expnumber - 1; k++)
cout << '0';
}
for (int i = 1; i < idx; i++) {//数字部分输出
if (expsign == '+') {//只在正数指数的时候做以下判断:
if (i < expnumber + 3)//如果数字长度还未到幂次长度则正常输出;
{
if (i != 2)
cout << data[i];
} else if (i == expnumber + 3)//如果数字长度等于幂次长度则输出小数点和数字;
{ cout << data[2] << data[i]; }
else cout << data[i];
}
else {
if (i != 2)
cout << data[i];
}
}
if (expsign == '+')//正数指数末位加零输出
{ for (int k = 0; k < (expnumber - idx + 3); k++) cout << '0'; }
cout << endl;
return 0;
}