C语言实现的 大数加法

注意:对于大数的加法,我们要做的是取用字符串来求解。不用整型数组的原因是如果其中一个大数为100000就不好界定其数组长度。代码如下:

CODE:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define MAX 1000
 4 #define ZEROCHAR -48// 0字符的ASC II值是48
 5 
 6 /* 取lengA和lengB中小的那个 */
 7 int MaxLeng(int a, int b)
 8 {
 9     return a>b? a:b;
10 }
11 
12 /* 化字符为数字 */
13 int TransNumber(char c)
14 {
15     return c-'0';
16 }
17 
18 int main()
19 {
20     char a[MAX], b[MAX];
21     memset(a, 0, sizeof(a));
22     memset(b, 0, sizeof(b));
23     while (scanf("%s %s", a, b)!=EOF)
24     {
25         int lengA = strlen(a);
26         int lengB = strlen(b);
27         printf("lengA = %d\n", lengA);
28         printf("lengB = %d\n", lengB);
29 
30         /* 把A和B字符串的顺序逆序排列 */
31         int i;
32         for (i = 0; i < (lengA+1)/2; ++i)
33         {
34             if (i == lengA-1-i) break;// 排除共奇数位个大数的影响
35             a[i] = a[i] + a[lengA-1-i];
36             a[lengA-1-i] = a[i] - a[lengA-1-i];
37             a[i] = a[i] - a[lengA-1-i];
38         }
39         for (i = 0; i < (lengB+1)/2; ++i)
40         {
41             if (i == lengB-1-i) break;// 排除共奇数位个大数的影响
42             b[i] = b[i] + b[lengB-1-i];
43             b[lengB-1-i] = b[i] - b[lengB-1-i];
44             b[i] = b[i] - b[lengB-1-i];
45         }
46 
47         /* 加运算 */
48         int maxLeng = MaxLeng(lengA, lengB);
49         int c;// 表示进位
50         int psum;
51         int sum[MAX];
52         int an, bn;
53         for (i = 0, c = 0, psum = 0; i <= maxLeng; ++i)
54         {
55             an = TransNumber(a[i]); bn = TransNumber(b[i]);
56             if (an == ZEROCHAR) an = 0;// 排除初始化中0字符的影响;
57             if (bn == ZEROCHAR) bn = 0;// 排除初始化中0字符的影响;
58             psum = an + bn + c;
59             sum[i] = psum%10;
60             c = psum/10;
61         }
62         int sumLeng = (sum[maxLeng]>0? maxLeng+1:maxLeng);// 最后一位若大于0总位数+1
63 
64         /* 逆序打印sum[] */
65         for (i = sumLeng - 1; i >= 0; --i)
66         {
67             printf("%d", sum[i]);
68         }
69         printf("\n");
70     }
71     return 0;
72 }

 

你可能感兴趣的:(C语言)