1001 A+B Format
Posted trebienba
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1001 A+B Format相关的知识,希望对你有一定的参考价值。
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
审题
题目给出两个整数a,b( −10^6≤a,b≤10^6),计算出它们的和sum,然后每三位用逗号隔开输出。
思路
因为a,b都没有超过int类型的范围,所以可知直接定义int类型计算。根据a,b的取值范围,可以得知sum不会超过10^7。因此可以把结果分为三类:
1.sum的位数大于6.
printf("%d,%03d,%03d", sum / 1000000, sum % 1000000 / 1000, sum % 1000);
2.sum的位数大于3小于6.
printf("%d,%03d", sum / 1000, sum % 1000);
3.sum的位数小于3。
printf("%d", sum);
参考代码
1 #include<stdio.h> 2 ? 3 int main(){ 4 int a, b, sum; 5 scanf("%d %d", &a, &b); 6 sum = a + b; 7 if(sum < 0){ 8 printf("-"); 9 sum = -sum; 10 } 11 12 if(sum >= 1000000){ //当位数大于6时 13 printf("%d,%03d,%03d", sum / 1000000, sum % 1000000 / 1000, sum % 1000); 14 } 15 else if(sum >= 1000){ //当位数大于3小于6时 16 printf("%d,%03d", sum / 1000, sum % 1000); 17 } 18 else{ //当位数小于等于3时 19 printf("%d", sum); 20 } 21 return 0; 22 }
以上是关于1001 A+B Format的主要内容,如果未能解决你的问题,请参考以下文章