《面向对象程序设计》第二次作业(1)(A+B问题)

作业记录:

问题描述与代码已上传github仓库object-oriented文件夹下

  • 题目一览
    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 Problem的改进版,要求输出三位一逗号形式的标准数字格式。

想到可用一个变量sum存放A+B的值,然后根据sum的长度分情况讨论。

本来在想要不要开个数组来存,但是观察到本题数字范围不大,最多只会出现两个逗号的情况。于是这题就可以简单明了的经判断语句分三种情况输出。虽然好几个elseif导致代码变长了长的丑点但是毕竟会可能导致的错误也少,反正是为了解决问题不是展示编程技巧的嗯。

然后在不同情况下用变量part1,2,3存放sum被逗号分开的数值分别输出。注意到sum的正负只要part1保留即可,于是对part2,3引入头文件math.h中的abs函数。

第一组测试数据:-1000000 9
输出:-999,991
第二组测试数据:-1000000 -9
输出:-1,0,9

立刻意识到把用逗号隔开的部分放不同变量输出的时候不能再用普通整型数值输出, 只要将part2,3输出时补上%03d即可。

第一组测试数据:-1000000 -9
输出:-1,000,009
第二组测试数据:-10000 1000
输出:-9,000
第三组测试数据:-10 10
输出:0

三种情况似乎都没什么问题,于是愉快地去提交了代码。第一次提交由于不熟悉PAT无意中提交成AWK……orz
第二次改成c就A了。

最终代码:

/*
三位一逗号的标准数字格式输出a+b 
*/
#include<stdio.h>
#include<math.h>
int main()
{
	freopen("xx.in","r",stdin);
	freopen("xx.out","w",stdout);
	int a,b;
	scanf("%d%d",&a,&b);
	int sum=a+b;
	int part1,part2,part3;//逗号间隔开最多三部分 
	
	if((abs(sum))<1000) 
	printf("%d",sum);//无逗号
	 
	else if((abs(sum))<1000000) //一逗号 
	{
		part2=sum%1000;
		part1=sum/1000;
	 	printf("%d,%03d",part1,abs(part2)); 
	}
	
	else //两逗号
	{
		part3=sum%1000;
		sum/=1000;
		part2=sum%1000;
		part1=sum/1000;	
		printf("%d,%03d,%03d",part1,abs(part2),abs(part3));
	}
	
	return 0;
}

posted @ 2016-01-26 21:32  thousfeet  阅读(412)  评论(4编辑  收藏  举报
/* */