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).
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.
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.
-1000000 9
-999,991
原先的代码:
#include<stdio.h> int main(){ int a, b, sum, count=0; int item[100]; count = 0; scanf("%d%d", &a, &b); sum = a+b; if (sum<0){ sum = -sum; printf("-"); } while(sum){ item[count++]= sum%1000; sum/=1000; } printf("%d", item[--count]); while(count>0){ printf(",%03d", item[--count]); } printf("\n"); return 0; }
结果在第四个测试点死活过不去,甚至通过二分查找的方式撞出了第四个测试点的数据(2与-2)
结果为0,但是本地上和pta测试出现差异的地方来了,pta输出结果为-2,本地显示为0
发现当sum为0时,打印的是item[-1],也就是b的位置(机组)
所以结果为0的时候就会输出b的值
本地不会出现这个问题可能是经过优化(不确定)
附上修改过后的代码
#include<stdio.h> main(){ int a, b, sum, count; int item[100]; scanf("%d%d", &a, &b); sum = a+b; count = 0; // 添加代码 if(!sum) printf("0"); // else{ if (sum<0){ sum = -sum; printf("-"); } while(sum){ item[count++]= sum%1000; sum/=1000; } printf("%d", item[--count]); while(count>0){ printf(",%03d", item[--count]); } printf("\n"); } return 0; }