I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
大数a+b也就是用字符串输入一串数字代表这个数字的大小,然后模拟一下加法的过程就可以了,为了方便计算把最低位个位放到第一个逆序计算比较方便
#include<stdio.h>
#include<string.h>
int main(void)
{
int a[1010],b[1010],c[1010],l1,l2,i,j,n,t,x,y=1;
char s1[1010],s2[1010];
scanf("%d",&t);
while(t--){
scanf("%s %s",s1,s2);
l1=strlen(s1),l2=strlen(s2);//计算长度
//初始化数组abc全为0
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
//把字符串s1 s2逆置存入数组a,b,逆序存方便计算
//就是把个位放到第一位依次往后递推
for(i=l1-1,j=0;i>=0;i--){
a[j++]=s1[i]-'0';
}
for(i=l2-1,j=0;i>=0;i--){
b[j++]=s2[i]-'0';
}
//这里计算a,b的每一位存入c
//这里应该就明白为什么把数组abc都初始化为0了把
//方便计算a+b就算长度不相等也可以利用0弥补,可以模拟一下加法过程。
//这也就是逆序存储的方便计算,后面加0不影响大小
for(i=0;i<1005;i++){
x=a[i]+b[i]+c[i];//如果进位了这里c[i]=1不进位就是0.
c[i]=x%10;//取余
c[i+1]=x/10;//进位
}
//找到第一个非0数就是最高位数,可以自己思考一下为什么
for(i=1005;i>=0;i--)
if(c[i]!=0)
break;
//输出要求
printf("Case %d:\n%s + %s = ",y,s1,s2);
//这里就要特判0+0了当结果为0的时候那么i就会从上次循环变为-1了
if(i==-1)
printf("0");
//输出计算结果
for(;i>=0;i--)
printf("%d",c[i]);
printf("\n");
//注意输出要求
if(t)
printf("\n");
y++;
}
}