大数的加法
给定任意位数长度的两个数,求它们数值之和计算出这两个任意位数长度的数之和。
样例输入
123451234512345 543215432154321
12.345 54.321
样例输出
666666666666666
66.666
# include<stdio.h> # include<string.h> int main() { int a[410], b[410], c[410], d[410], flag2; int i, j, k, len1, len2; char s1[410], s2[410]; while(scanf("%s%s", s1, s2) != EOF) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(c, 0, sizeof(c)); memset(d, 0, sizeof(d)); len1 = strlen(s1); flag2 = 1; for(i = 0; s1[i]; i++) if(s1[i] == '.') break; k = 0; for(j = i - 1; j >= 0; j--) a[k++] = s1[j] - '0'; k = 0; //存小数部分,并把个位作为吧b[0](3) b[k++] = 0; if(i < len1 - 1) for(j = i + 1; s1[j]; j++) b[k++] = s1[j] - '0'; len2 = strlen(s2); for(i = 0; s2[i]; i++) if(s2[i] == '.') break; k = 0; for(j = i - 1; j >= 0; j--) c[k++] = s2[j] - '0'; k = 0; d[k++] = 0; if(i < len2 - 1) for(j = i + 1; s2[j]; j++) d[k++] = s2[j] - '0'; for(i = 0; i < 410; i++) { a[i] += c[i]; if(a[i] >= 10) { a[i + 1]++; a[i] -= 10; } } for(i = 409; i >= 1; i--) { b[i] += d[i]; if(b[i] >= 10) { b[i - 1]++; b[i] -= 10; } } a[0] += b[0]; for(i = 0; i < 410; i++) if(a[i] >= 10) { a[i + 1]++; a[i] -= 10; } i = 409; while(a[i] == 0 && i >= 0) i--; while(i >= 0) { printf("%d", a[i]); i--; } i = 409; while(b[i] == 0 && i >= 1) i--; if(i == 0) flag2 = 0; if(flag2 == 0) printf("\n"); else if(flag2 == 1) { printf("."); for(j = 1; j <= i; j++) printf("%d", b[j]); printf("\n"); } } return 0; }
[color=#0000FF]#include<stdio.h> #include<string.h> void add(char a[],char b1[]); int main() { char a[1000],b[1000]; int n,i; int len1,len2; scanf("%d",&n); for(i=1; i<=n; i++) { scanf("%s %s",a,b); len1=strlen(a); len2=strlen(b); printf("Case %d:\n%s + %s = ",i,a,b); if(len1>=len2) add(a,b); else add(b,a); if(i!=n) printf("\n"); } return 0; } void add(char a[],char b1[]) { int c[1000]; char b[1000], *p=b; int len1,len2,i,t; len1=strlen(a); //默认 l>=k len2=strlen(b1); p=p+len1-len2; memset(b,'0',len1-len2); //目的是字符串右对齐,b数组中前面空着的地方用 '0' 填充 sscanf(b1,"%s",p); //将b1中的字符串放到 b数组 填充 ‘0’后面的部分 for(t=0,i=len1-1; i>=0; i--) { c[i]=a[i]-'0'+b[i]-'0'+t; if(c[i]>=10&&i!=0) { c[i]=c[i]-10; t=1; } else if(c[i]<10) t=0; } for(i=0; i<len1; i++) printf("%d",c[i]); printf("\n"); } //Sample Input //2 //1 2 //112233445566778899 998877665544332211 // // //Sample Output //Case 1: //1 + 2 = 3 // //Case 2: //112233445566778899 + 998877665544332211 = 1111111111111111110 。