杭电1002_C语言

来源:互联网 发布:淘宝的淘气值是干嘛的 编辑:程序博客网 时间:2024/06/11 19:08

题目描述

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B. 
 

输入格式

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. 
 

输出

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. 
 

样例输入

2
1 2
112233445566778899 998877665544332211

样例输出

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110



原创AC代码:

#include<stdio.h>#include<string.h>int main(){int t,i,j=0;char ax[1010],bx[1010];int a[1010],b[1010],an,bn,mn,sum[1020];scanf("%d",&t);while(t--){j++;memset(a,0,sizeof(a));memset(b,0,sizeof(b));scanf("%s %s",&ax,&bx);an=strlen(ax);bn=strlen(bx);if(an>bn) mn=an;else mn=bn;//转移数组数据char>>intfor(i=0;i<an;i++) a[i]=ax[an-1-i]-48;for(i=0;i<bn;i++) b[i]=bx[bn-1-i]-48;//开始计算for(i=0;i<=mn;i++){if(a[i]+b[i]>9) a[i+1]+=1;sum[i]=(a[i]+b[i])%10;}//输出结果if(sum[mn]==0) mn--;printf("Case %d:\n",j);printf("%s + %s = ",ax,bx);for(i=mn;i>=0;i--) printf("%d",sum[i]);if(t==0) printf("\n");else printf("\n\n");}}


后来自己又写了一次,原理差不多,但是实现不一样只用了a,b,sum三个数组

#include<stdio.h>#include<string.h>int main (){int t,i,d,la,lb,sa,sb,y,n;char a[1010],b[1010],sum[1010];scanf("%d",&t);n=t;while(t--){scanf("%s %s",&a,&b);memset(sum,0,sizeof(sum));la=strlen(a);lb=strlen(b);if(la>lb)d=la;else d=lb;//开始计算for(y=0,i=0;i<=d;i++){if(la-1>=0) sa=a[--la]-'0';else sa=0;if(lb-1>=0) sb=b[--lb]-'0';else sb=0;sum[i]=(sa+sb+y)%10+'0';y=(sa+sb+y)/10;}//输出结果printf("Case %d:\n%s + %s = ",n-t,a,b);if(sum[d]=='0')d--;for(i=d;i>=0;i--)printf("%c",sum[i]);printf("\n\n");}}


0 0
原创粉丝点击