同PAT 1073. Scientific Notation
字符串模拟,不难的。
先用字符串digits记录所有的数字,可确保有效位数不变;再用整型exp记录指数大小。
我在处理那种结果中不带小数点的时候出现了错误 —— exp + 1 >= digits.size(), 即exp + 1 <= digits.size() 时就会出现不带小数点的情况,此时cout.width的参数应为( exp+1 ).
如Sample -1.2E+10应该是11位... 之前只输出了10位,一直没发现。
以后提交代码,一定要看清sample是不是全过了。
代码:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
inline int string_to_int(const string& str)
{
int ret;
stringstream ss;
ss << str;
ss >> ret;
return ret;
}
int main()
{
string num, digits;
int exp;
cin >> num;
int cut = num.find('E');
exp = string_to_int( num.substr(cut+1) );
digits = num[1];
digits += num.substr(3, cut - 3);
if (num[0] == '-')
{
cout << '-';
}
if ( exp < 0 )
{ // digits都在0.后面
if (exp == -1)
{
cout << "0." << digits << endl;
} else
{
cout << "0.";
cout.width(-exp-1);
cout.fill('0');
cout << 0;
cout << digits << endl;
}
} else if (exp < digits.size() - 1)
{ // digits在小数点两侧
cout << digits.substr(0, exp+1);
cout << ".";
cout << digits.substr(exp+1);
} else
{ // 没有小数点
cout.flags(ios::left);
cout.width(exp+1); // 要+1...
cout.fill('0');
cout << digits;
}
return 0;
}