您的位置:首页 > 其它

PAT-PAT (Advanced Level) Practise 1001. A+B Format (20) 【二星级】

2015-08-20 10:09 417 查看
题目链接:http://www.patest.cn/contests/pat-a-practise/1001

题面:

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,以每三位加一个逗号的格式。

解题:

注意后面部分如果小于100需加前缀0。

代码:

#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
	int a,b,ans;
    cin>>a>>b;
    ans=a+b;
	if(ans<0)
	{
		cout<<"-";
		ans=-ans;
	}
	if(ans<1000)
		cout<<ans<<endl;
	else if(ans<1000000)
		cout<<ans/1000<<","<<fixed<<setw(3)<<setfill('0')<<ans%1000<<endl;
	else
		cout<<ans/1000000<<","<<fixed<<setw(3)<<setfill('0')<<ans/1000-ans/1000000*1000<<","<<fixed<<setw(3)<<setfill('0')<<ans%1000<<endl;
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: