具体要求
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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10的6次方≤a,b≤10的6次方,The numbers are separated by a space.
Output Specification:
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
具体思路
基础的题,我用了数组来储存了这个结果数的每个位的数,同时需要先进后出,所以可以理解为顺序栈吧。
具体代码
#include<stdio.h>
#include<math.h>
#define MAX 100
int main()
{
int i,j,m,n,k,g,as[MAX]={0};/*变量定义太多了,有更好的可以自己选择*/
g=0;/*记录这个数有多少位*/
scanf("%d %d",&m,&n);/*输入*/
m=m+n;/*结果*/
k=0;
j=m;
i=abs(j)%10;/*i为j的个位数*/
k=j;/*存储上一个j*/
j=j/10;/*j开始移位*/
while(j)/*j不为0,即上一个j(k)的绝对值大于9*/
{
as[g++]=i;/*进栈*/
i=abs(j)%10;/*i继续为j的个位数*/
k=j;/*存储上一个j*/
j=j/10;/*j继续移位*/
}
as[g]=k;/*将k加入数组此时为k为原数的首位*/
j=0;
for(i=g;i>=0;i--)
{
printf("%d",as[i]);/*输出,倒序的,等同于出栈*/
if((g-j)%3==0&&i!=0)
printf(",");/*当数组中后面的数是3的倍数且不为0,输出一个逗号*/
j++;
}
return 0;
}
具体结果
题很简单,就有些特殊情况而已,我也在进步学习,代码很多不足,仅供参考。