A + B Problem II
Problem Description
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
这道题是一个简单的高精度加法,对于第一次接触大数的人来说可能会有点难,一般都是因为不懂得原理。
所以只要理解了原理,就会变得简单了。
大数相加,由于已经超出了C的数值范围,所以我们只能将我们的数值用字符串处理,然后通过模拟
我们在草稿纸上打草稿。
下面是我写的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[1000],b[1000],sum[1001];
int la,lb,t,i,j,f,n,max,temp,carry;
scanf("%d",&t);
for(n=1;n<=t;n++)
{
carry=0;
scanf("%s%s",a,b);
printf("Case %d:\n",n);
printf("%s + %s = ",a,b);
la=strlen(a)-1;lb=strlen(b)-1; //读出两个数的长度,用于后面计算
max=la>lb? la:lb;
//首先要将两个数右对齐,也就是个位对齐,然后模拟我们平时打草稿
for(i=la,j=lb,f=max;i>=0 || j>=0;i--,j--,f--)
{
temp=carry; //用于进位
if(i>=0) temp+=a[i]-'0'; //注意:相加的时候要转换为数值
if(j>=0) temp+=b[j]-'0';
if(temp>9) //如果相加大于9的话就要进位
{
sum[f]=temp-10+'0';
//计算完后要记得转换为字符,也可以不转换,这就要看你前面是怎么定义的
carry=1;
}
else
{
sum[f]=temp+'0';
carry=0;
}
}
if(carry==1) printf("1"); //这里是用来进位的,就是处理像5+5=10的这类情况。
for(i=0;i<=max;i++)
printf("%c",sum[i]);
if(n==t) printf("\n");
else printf("\n\n");
}
return 0;
}