解题过程的小记录,如有错误欢迎指出。
简单题,没时间可以不复习
题目分析
将一定格式的科学计数法数字转化为传统计数法进行显示。
注意点
注意指数为0的特殊情况,但本题的检测点并不能检测出区分与没区分的区别,换而言之,没写0的特例分支也不会报错。
我的解题过程
思路
先找出系数和10的指数的大小,然后按照指数的正负进行分类输出数字(左移或者右移/加0还是加小数点)
bug
中途有点搞错x=x10+1和x+=x10的区别导致指数的读取有点错误。还好中途就进行了输出查看是否有出错,没有沦落到最后debug崩溃境地。
代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string sci_notion;
char sign1, sign2;//用来分别表示系数部分和指数部分的正负
cin >> sci_notion;
sign1 = sci_notion[0];
vector<char> num, result;
int i;
for (i = 1; i < sci_notion.size(); i++) {
if (sci_notion[i] != 'E') {
if(isdigit(sci_notion[i]))
num.push_back(sci_notion[i]);
}
else break;
}
sign2 = sci_notion[++i];
if (sci_notion[i + 1] == '0') i++;
int exp = 0;//指数
for (i++; i < sci_notion.size(); i++) {
exp = exp * 10 + sci_notion[i] - '0';//易错点:不要搞错+=的关系
}
if (sign2 == '+') {
if (exp > num.size() - 1) {
result = num;
exp = exp - (num.size() - 1);
for (i = 0; i < exp; i++) {
result.push_back('0');
}
}
else if (exp == num.size() - 1) {
result = num;
}
else {
result.push_back(num[0]);
for (i = 1; i <= exp; i++) {
result.push_back(num[i]);
}
result.push_back('.');
for (i; i < num.size(); i++) {
result.push_back(num[i]);
}
}
}
else {
result.push_back('0');
result.push_back('.');
for (i = 0; i < exp - 1; i++) {
result.push_back('0');
}
for (i = 0; i < num.size(); i++) {
result.push_back(num[i]);
}
}
if (sign1 == '-') cout << sign1;
for (i = 0; i < result.size(); i++) {
cout << result[i];
}
return 0;
}
dalao的代码
全部代码因版权原因不放出来,大家可以自行去柳神博客购买~
借鉴点
- 利用了string.substr(start,len)来截取字符串,十分简洁
【string.substr()f返回一个子字符串,从其指定的位置开始】
string t = s.substr(1, i-1);
- 采用stoi(string)进行string到int的转换,s.substr()第二个参数缺省则默认截取到字符串尾
【PAT算法题中常用int转string=.>to_string()以及string转int】
int n = stoi(s.substr(i+1));
- 直接获取了含正负的指数值,可以用abs()进行转换来get指数的绝对值大小从而找到输出0的规律
for (int j = 0; j < abs(n) - 1; j++) cout << '0';