题目
链接:PAT (Advanced Level) Practice 1001 A+B Format
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
. 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
思路
题目大意是输入两个取值范围在和
之间的整数,求它们的和,并输出,输出格式要每隔3位数输出一个逗号,如示例。
所以思路就是分多次输出,因为两数和最大也只有7位数,所以穷举各种可能性即可。
代码
#include<stdio.h>
int main(){
int a, b, sum;
scanf("%d %d", &a, &b);
sum = a + b;
if(sum < 0){
printf("-");
sum = -sum;
}
if(sum >= 1000000){ //当位数大于6时
printf("%d,%03d,%03d", sum / 1000000, sum % 1000000 / 1000, sum % 1000);
}
else if(sum >= 1000){ //当位数大于3小于6时
printf("%d,%03d", sum / 1000, sum % 1000);
}
else{ //当位数小于等于3时
printf("%d", sum);
}
return 0;
}
---END---
网友评论