题目

14分的解法
点击查看代码
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int toInt(string s){
int ans = 0;
for(int i =0;i<int(s.size());i++){
ans = ans *10 + (s[i]-'0');
}
return ans;
}
int main(){
string input; cin>>input;
// 若无正数,则省略+号;若为负数,则输出时先输出-号
if(input[0]=='-') cout<<'-';
if(input == "0"){
cout<<0;
return 0;
}
// 找到E后面的数,若为+号,则在后面补0;若为-号,则在前面补0
int pos = input.find('E');
int ppos = input.find('.');
string exp = input.substr(pos+1);
int zeroNum = toInt(exp.substr(1));
if(zeroNum==0){
cout<<input.substr(1,ppos-1)<<input.substr(ppos,pos-ppos);
return 0;
}
if(exp[0]=='-'){
cout<<"0.";
for(int i =0;i<zeroNum-1;i++){
cout<<"0";
}
cout<<input.substr(1,ppos-1)<<input.substr(ppos+1,pos-ppos-1);
}else{
cout<<input.substr(1,ppos-1)<<input.substr(ppos+1,pos-ppos-1);
for(int i =0;i<zeroNum-1;i++){
cout<<"0";
}
}
return 0;
}
当 E+ 时,未正确处理小数点后数字个数不够的情况
满分解法
点击查看代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cin >> input;
// 解析符号
int indexE = input.find('E');
char sign = input[0]; // 可能是 '+' 或 '-'
// 解析底数部分
string base = input.substr(1, indexE - 1);
int dotIndex = base.find('.');
// 解析指数部分
int exp = stoi(input.substr(indexE + 1)); // 获取指数部分的数值
// 去掉小数点
base.erase(dotIndex, 1); // 移除小数点
// 输出符号
if (sign == '-') cout << '-';
// 处理指数为负数的情况 (E-)
if (exp < 0) {
cout << "0.";
for (int i = 1; i < -exp; i++) cout << '0'; // 补零
cout << base; // 输出剩下的数字
}
// 处理指数为正数的情况 (E+)
else {
int len = base.length();
if (exp >= len - 1) { // 需要在后面补 0
cout << base;
for (int i = 0; i < exp - (len - 1); i++) cout << '0';
} else { // 需要在中间插入小数点
cout << base.substr(0, exp + 1) << '.' << base.substr(exp + 1);
}
}
return 0;
}
浙公网安备 33010602011771号