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<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的位置(机组)
1001 A+B Format (20 分)
所以结果为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; 
}
上一篇:第二章Nginx服务器的安装、升级详情


下一篇:hdu 6982 / 2021“MINIEYE杯”中国大学生算法设计超级联赛(3)1010 Road Discount(二分+最小生成树)