1001. A+B Format (20)题解

git链接

作业描述

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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的和并以千分位的形式输出。我首先注意到a,b的取值范围为-1000000 <= a, b <= 1000000,可以对a,b和sum的大小进行分类讨论,但是考虑到这个解法对a,b的取值有较大的限制,我选择了新的思路,就是将sum每个位的数字转化为字符型存储在一个数组中,再每隔三位插入一个逗号。

第一次代码

#include<stdio.h>
#include<math.h>
int main() 
{
	int a,b,sum,c,i,j,count=0;
	char s[9]; 
	scanf("%d%d",&a,&b);
	sum=a+b;
	c=abs(sum);
	if(c<1000)
	printf("%d",sum);
	else
    {
	for(i=0;i<=9;i++)
	{
	    s[i]=sum%10+48;
		sum=sum/10;
		count++;
		if(sum==0)break;
		if(count%3==0)
		s[++i]=',';
	}
	for(;i>=0;i--)
	printf("%c",s[i]);
    }
    return 0;
}

写完代码后提交的结果如下,出现了一些三个答案错误,那应该是有些细节没有考虑到,在审视了题目和代码后发现没有考虑到sum为负数的情况,于是对这种情况进行了补充。

修改后的代码

#include<stdio.h>
#include<math.h>
int main() 
{
	int a,b,sum,c,i,j,count=0;
	char s[9]; 
	scanf("%d%d",&a,&b);
	sum=a+b;
	c=abs(sum);
	if(c<1000)
	printf("%d",sum);
	else
    {
	for(i=0;i<=9;i++)
	{
	    s[i]=sum%10+48;
		sum=sum/10;
		count++;
		if(sum==0)break;
		if(count%3==0)
		s[++i]=',';
	}
	for(;i>=0;i--)
	printf("%c",s[i]);
    }
    return 0;
}

提交之后全部正确

做题中遇到的问题

这次代码题中遇到的主要问题就是如何将整数转化为字符,后来通过百度知道可以通过+'0'或者+48完成,不过原理没搞懂。

posted on 2017-02-02 01:02  湖心海底  阅读(627)  评论(2编辑  收藏  举报

导航