1001 A+B Format (20 分)

2021/7/27 6:07:52

本文主要是介绍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的位置(机组)

所以结果为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; 
}


这篇关于1001 A+B Format (20 分)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程