大数加法

来源:互联网 发布:黑蚂蚁成人的网络电视 编辑:程序博客网 时间:2024/05/22 11:34
#include <stdio.h>#include <string.h>#define N 100void charstoint(int a[], char s[]){int i;int len = strlen(s);memset(a,0,4*N);   //整型占4个字节for (i=0; i<len; i++){//不考虑负数与非数字字符的情况a[len-1-i] = s[i] - '0'; //将每一个字符转化为数字逆序存放在整型数组中,例如字符串 123456 -> a[0] = 6,a[1] = 5, ...a[5] = 1;}}void add(int a[], int b[], int c[]){int i;memset(c,0,4*(N+1)); for (i=0; i<N; i++){c[i] = a[i] + b[i]; }for (i=0; i<N+1; i++)  //处理进位{c[i+1] += c[i] / 10;c[i] = c[i] % 10;}}int main(){int i,j = N;int a[N],b[N],c[N+1];char s1[N],s2[N];printf("input the first number:");    gets(s1);    printf("input the second number:");    gets(s2);charstoint(a,s1);charstoint(b,s2);add(a,b,c);while(c[j]==0)   //去掉多余的0{j--;}for (i=j; i>=0; --i)  //打印结果{printf("%d",c[i]);}printf("\n");return 0;}