2017寒假作业二之代码题

GitHub的链接
pdf

  1. 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
    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在一行的总和。之和必须用标准的格式。
样本值输入
-1000000,9
样本值输出
-999,991

解题思路:

我的第一个想法很直接:
首先主代码不用说就是用来实现a+b的,然后关键在sum的处理上,所以我很快写出一段代码,采用内外函数,这样我就可以在出现bug的时候只修改外函数。代码如下:

#include<stdio.h>
int main()
{
	void print(long int sum);
	long int num_one,num_two,sum;
	scanf("%ld%ld",&num_one,&num_two);
	sum=num_one+num_two;
	print(sum);
	return 0;
}
void print(long int sum)
{
	if(sum>=0)
	{
		if(sum/100-9<=0) printf("%ld\n",sum);
		else printf("%ld,%ld\n",(sum-sum%1000)/1000,sum%1000);
	}
	else
	{
		if((-1)*sum/100-9<=0) printf("%ld\n",sum);
		else printf("%ld,%ld\n",(sum-sum%1000)/1000,(-1)*sum%1000);
	}
	return;
}

提交结果好像不太对。。。

嘿嘿,所以这段代码是有问题的--因为我只考虑到六位数,而题设最多达七位数,而且我还忘了补齐‘0’,然后就出现了以下结果:

于是我做了以下修改:

  • 首先,分正负太麻烦了,于是我用abs()函数代替if。
  • 然后是分三个区间考虑对sum做的分割。
  • 最后在需要补齐的输出部分使用“%03ld”形式就可以了。
    这是修改之后的代码:
#include<stdio.h>
#include<math.h>
//主函数,计算sum
int main()
{
	void print(long int sum);
	long int num_one,num_two,sum;
	scanf("%ld%ld",&num_one,&num_two);
	sum=num_one+num_two;
	print(sum);      //对sum进行处理
	return 0;
}
void print(long int sum)
{
	long int num_three;  //num_three用来储存绝对值sum
	int p,q,t;        //用来储存每三个数的分块
	num_three=abs(sum);
	if(num_three<1000&&num_three>=0)
		printf("%ld\n",sum);
	if(num_three>=1000&&num_three<1000000)
	{
		p=num_three%1000;
		q=sum/1000;
		printf("%ld,%03ld\n",q,p);
	}
	if(num_three>=1000000)
	{
		p=num_three%1000;
		q=(num_three%1000000)/1000;
		t=sum/1000000;
		printf("%ld,%03ld,%03ld\n",t,q,p);
	}
	return;
}

提交后倒是对了

最后是总的提交列表

posted @ 2017-01-26 19:02  溯説  阅读(201)  评论(1编辑  收藏  举报