PAT (Advanced Level) Practice 1001 A+B Format (20 分)(C++)(甲級)

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

Each input file contains one test case. Each case contains a pair of integers a and b where −10​6≤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


#include <cstdio>
#include <cstring>
#include <cmath>

int main()
{
	int a = 0, b = 0;
	scanf("%d %d", &a, &b);
	int sum = a + b;
	int S[5] = { 0 };//輔助棧
	int top = -1;//棧頂指針
	if (!sum) { printf("0"); return 0; }//和爲0直接輸出了
	if (sum < 0) { printf("-"); sum = -sum; }//和爲負數先輸出符號,之後正負格式統一
	while (sum)
	{
		S[++top] = sum % 1000;
		sum /= 1000;
	}
	printf("%d", S[top--]);//第一個逗號之前不需要補零
	while (top >= 0) printf(",%03d", S[top--]);//注意輸出格式
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章