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是不是全过了。


另,cout的输出格式可去查文档。我参考了点击打开链接


代码:

#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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值