题目来源:http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1004&cid=31343&problem=Problem%20%20D
解法或类型:循环结构。
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 consistsof 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 assumethe 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 isthe an equation "A + B = Sum", Sum means the result of A + B. Notethere are some spaces int the equation. Output a blank line between two testcases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
题意描述
给两个数算出它们的和,并以题目给出的形式输出。
解题思路
把给出的两个数以字符串的形式输入,然后把两个字符串的内容分别存入倒序两个数组a,b中(方便后面相加),然后让两个数组的从第一个数依次相加,每次相加的值若大于9,则存入c[i]中的减10,c[i+1]的值加1,反之直接存入c[i]。
时空分析:
程序代码:
#include<stdio.h>
#include<string.h>
intmain()
{
char a[1010],b[1010];
intd[30][1010],e[30][1010],f[30][1020],g[30],h[30],v[30],j,l1,l2,m,n,c,i,t,y,u,k;
while(scanf("%d",&m)!=EOF)
{
for(c=0;c<30;c++)//给二维数组初始化时只进行了一次
{
for(i=0;i<1010;i++)
{
d[c][i]=0;
e[c][i]=0;
f[c][i]=0;
}
}
c=0;
n=m;
while(m--)
{
l1=0;
l2=0;
scanf("%s",a);
scanf("%s",b);
l1=strlen(a);
l2=strlen(b);
t=0;
for(i=l1-1;i>=0;i--)
{
d[c][t]=a[i]-'0';
t++;
}
y=0;
for(i=l2-1;i>=0;i--)
{
e[c][y]=b[i]-'0';
y++;
}
g[c]=t;
h[c]=y;
if(t>y||t==y)
{
u=0;
for(i=0;i<=t;i++)
{
f[c][u+1]=0;
f[c][u]=f[c][u]+d[c][i]+e[c][i];
if(f[c][u]>9)
{
f[c][u]=f[c][u]-10;
f[c][u+1]=f[c][u+1]+1;
}
u++;
}
}
if(t<y)
{
u=0;
for(i=0;i<=y;i++)
{
f[c][u+1]=0;
f[c][u]=f[c][u]+d[c][i]+e[c][i];
if(f[c][u]>9)
{
f[c][u]=f[c][u]-10;
f[c][u+1]=f[c][u+1]+1;
}
u++;
}
}
v[c]=u;
c++;
}
for(k=0;k<c;k++)
{
printf("Case %d:\n",k+1);
//printf("v[k]==%d\n",v[k]);printf("f[v[k]-1]==%d",f[k][v[k]-1]);
for(i=g[k]-1;i>=0;i--)
{
printf("%d",d[k][i]);
}
printf(" + ");
for(i=h[k]-1;i>=0;i--)
{
printf("%d",e[k][i]);
}
printf(" = ");
if(f[k][v[k]-1]==0)
{
for(i=v[k]-2;i>=0;i--)
{
printf("%d",f[k][i]);
}
}
else
{
for(i=v[k]-1;i>=0;i--)
{
printf("%d",f[k][i]);
}
}
//printf("\n%d%d",k,n);
if(k<n-1)
{
printf("\n\n");
}
else
{
printf("\n");
}
}
}
return 0;
}
错误分析:
1、输出错误这题是输出完之后,才出结果,我写的是输入两个数出一个结果。
2、输出需要控制次数且每次输出的内容都需要先存入一个地方,需要用二维数组开始用的一维。
3、第一次的结果输出后,在输入几组数据结果错误,没有对二维数组的值初始化为0.