1001 A+B Format——PAT甲级

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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

Output Specification:

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的和进行讨论,小于1000直接打印,大于等于1000且小于1000000的数有且仅有一个逗号,因此除以1000输出千位上的数并输出一个逗号,对1000取余得到剩下三位,注意,要以%03d的形式输出余数,因为它的余数一定是三位,就比如1000,要把000输出的;剩下的大于等于1000000的是一个道理。

想提醒大家一下:输出的时候一定是从右往左每三位输出一个逗号,不是从左往右,就好比1000000,要输出1,000,000而不是100,000,0。第一次写好多个测试点不过,也不知道是什么问题,不知道有没有人和我一样啊!!!

#include<iostream>
using namespace std;

int main() {
	int a, b;
	cin >> a >> b;
	int sum = a + b;
	if (sum < 0) cout << "-";
	sum = abs(sum);
	if (sum < 1000) printf("%d", sum);
	else if (sum >= 1000 && sum < 1000000) printf("%d,%03d", sum / 1000, sum % 1000); 
	else printf("%d,%03d,%03d", sum / 1000000, sum % 1000000 / 1000, sum % 1000);  
	
	return 0;
}


版权声明:本文为TJH_00原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。