PAT甲级1001. A + B Format(20)

1001. A + B Format(20)
Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas(unless there are less than four digits).
Input
Each input file contains one test case.Each case contains a pair of integers a and b where - 1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line.The sum must be written in the standard format.
Sample Input
- 1000000 9
Sample Output

- 999, 991

翻译:

A+B格式化

计算a+b并且以标准格式输出他们的和,数字必须用逗号分成三个一组(除非不到4个数字)

输入:

每个输入文件包含一个实例。每个样例包含一对数字a和b,a和b范围是 - 1000000 <= a, b <= 1000000。这两个数字用空格分开。

输出:

对于每一个实例,你要在一行中输出a和b的和。和必须用标准格式书写。

样例输入:

- 1000000 9
样例输出:

- 999, 991

分析:我们可以分成两步来完成。第一步,先把a与b的和转化成一个字符串。第二步,从个位数开始,每3个数字插入一个逗号,要注意的是不能在最前端加逗号。

另外为了不分正负讨论,对于负数,我们可以输出负号,然后再把负号从字符串中抹去。

这是一篇关于字符串的插入与删除操作的小介绍

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int main()
{
	int a, b, i;
	cin >> a >> b;
	char c[10];
	sprintf(c, "%d", a + b);
	string s = c;//数字转字符串

	string temp = ",";//temp字符串代表逗号
	if (a + b < 0)	//如果和小于0
	{
		cout << "-";//先输出负号
		s.erase(0, 1);//再把负号抹去
	}
	for (i = s.length() - 3; i > 0; i -= 3)//从倒数第3个字符开始,每隔3个插入一个逗号
		s.insert(i, temp);
	cout << s;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值