天天看點

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;
}
           

送出結果好像不太對。。。

2017寒假作業二之代碼題

嘿嘿,是以這段代碼是有問題的--因為我隻考慮到六位數,而題設最多達七位數,而且我還忘了補齊‘0’,然後就出現了以下結果:

2017寒假作業二之代碼題

于是我做了以下修改:

  • 首先,分正負太麻煩了,于是我用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;
}
           

送出後倒是對了

2017寒假作業二之代碼題

最後是總的送出清單

2017寒假作業二之代碼題