a+b 翻译 分析 代码
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).
【计算a+b的值,并以标准格式输出--那意味着所得答案每三位会被“,”分为一个组】
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.
【每个输入的文件都包括一个测试用例。每种情况都包含一对正数A和B,其中1000000<=A,B<=1000000。这些数字被空格分隔开。】
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.
【对每个测试数据,需要在一行里面输出a+b的总值,所得总值要用标准格式输出】
【注】:以下分析所在为代码注释,通过注释可以分析得到此题答案。
【注】:此代码是由Dev c++ 5.11 所写,运用c语言, 其他方法例如c++。
****************************************************************************************************************************
#include
#include
int main()
{
int a,b,sum,len=0;
int c[20]={0};
scanf("%d%d",&a,&b);
sum=a+b;
//此段为最后倒序输出的数组添加负号情况 ,最终测试时释放注释。
if(sum<0)
{
printf("-");
sum=-sum; //将负数变正数,否则在存入数组的时候会使数组每个值都存为负值!!!
}
if(sum==0)
{
printf("0\n");
// printf("1"); 如果相加等于零的话,所得sum的位数为1位。 运行程序时,去掉此段。
return 0;
}
// printf("%d\n",sum); //此段测试a+b是否计算正确 ,运行程序时,去掉此段
//接下来写结果带入数组
/*******************倒序置入数组***********************************************/
while(sum) //当sum不等于0的时候 76/10=7,7%10=7,将7置入最后数组最后一位
{ c[len++]=sum%10; //把sum结果倒叙置入数组
sum=sum/10;
}
// printf("%d\n",len); //测试用sum长度
/******************************************************************************/
//text:倒序输出数组
while(len--)
{
//进阶 判断位数,添加逗号
printf("%d",c[len]);
if(len%3==0&&len!=0)
{
printf(",");
}
}
return 0;
}
****************************************************************************************************************************
测试点: 999999 2
-999999 -2
-2 2
120 3