PAT (Advanced Level) Practice 1001 A+B Format (20 分)(C++)(甲級)
阿新 • • 發佈:2019-01-02
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 −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
#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;
}