写在前面
- 实现思路(基础)
- 读入字符串,循环定位字符E位置
- 判断正负号,输出
- 指数正,考虑是否补零;负,考虑小数点位置
- 注意
- 指数为0输出形式
- 新题型,实现较负责。a题时间45分钟(偏长)
测试用例
input:
+1.23400E-03
output:
0.00123400
input:
-1.2E+10
output:
-12000000000
input:
+3.1415E+004
output:
31415
input:
-3.1415926E-0005
output:
-0.000031415926
ac代码(C++)
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char str[10010];
scanf("%s", str);
int len = strlen(str);
if(str[0] == '-') printf("-");
int pos = 0;
while(str[pos] != 'E') pos++;
int exp = 0;
for(int i = pos + 2; i < len; i++) exp = exp * 10 + (str[i] - '0');
if(exp == 0) for(int i=1; i<pos; i++) {
printf("%c", str[i]); // 指数为0,幂因数为1.直接输出另一因数
return 0;
}
if(str[pos+1] == '-')
{
printf("0."); // 以0开头
for(int i=0; i<exp-1; i++) printf("0");
printf("%c", str[1]); // 输出整数
for(int i=3; i<pos; i++) printf("%c", str[i]);
}
else
{
for(int i=1; i<pos; i++)
{
if(str[i] == '.') continue;
printf("%c", str[i]);
if((i==exp+2) && (pos-3 != exp)) printf(".");
}
for(int i=0; i<exp-(pos-3); i++) printf("0");
}
return 0;
}
- 注意:如果使用
gets
函数,更换头文件并调整编译语言
#include <stdio.h>
gets(str);
#include<string.h>
int len = strlen(str);
学习代码
-实现思路
- 分别存储尾数、指数
- 通过stoi
函数将指数字符串转数字
- 指数小于0,直接尾数小数点后补0输出
- 指数等于0,输出尾数
- 指数大于0,计算尾数小数部分长度与指数差值,指数大补0;指数小在尾数部分打印小数点
- 参考代码
#include <iostream>
using namespace std;
int main()
{
string s;
cin >> s;
int i = 0;
while (s[i] != 'E') i++;
string t = s.substr(1, i-1);
int n = stoi(s.substr(i+1));
if (s[0] == '-') cout << "-";
if (n < 0) // 指数为负
{
cout << "0.";
for (int j = 0; j < abs(n) - 1; j++) cout << '0';
for (int j = 0; j < t.length(); j++)
if (t[j] != '.') cout << t[j];
}
else // 指数为正
{
cout << t[0];
int cnt, j;
for (j = 2, cnt = 0; j < t.length() && cnt < n; j++, cnt++) cout << t[j];
if (j == t.length()) // 指数大于尾数小数点后数字长度
{
for (int k = 0; k < n - cnt; k++) cout << '0';
}
else // 指数小于尾数小数点后数字长度
{
cout << '.';
for (int k = j; k < t.length(); k++) cout << t[k];
}
}
return 0;
}
涉及函数
- C++,int也被成为
long int
; long long 也被称为long long int
stoi / atoi / strtol // 字符串转整数
strlen // char类型存储字符串,获取字符串长度