大整数加法.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  /**

   计算两个大整数的和,输入:a和b分别使用字符串表示的两个大整数,输出:c是a和b的和

  */

  1. void sum(char *a, char *b, char *c) {
  2.    int i, j, k;
  3.    int len1 = strlen(a);
  4.    int len2 = strlen(b);
  5.    k = (len1 > len2) ? len1: len2;
  6.    memset(c, '0', k);
  7.    c[k+1] = '\0';
  8.    int carry = 0, temp;
  9.    for(i=len1-1, j=len2-1; i>=|| j>=0; i--, j--, k--)
  10.    {
  11.       temp = carry;
  12.       if(i>=0) temp += a[i] - '0';
  13.       if(j>=0) temp += b[j] - '0';
  14.       
  15.       if (temp >= 10) {
  16.          c[k] = temp - 10 + '0';
  17.          carry = 1;
  18.       } else {
  19.          c[k] = temp + '0';
  20.          carry = 0;
  21.       }
  22.    }
  23.    c[k] = carry + '0';
  24. }

  25. int main()
  26. {
  27.    char a[200], b[200], c[200], *p;
  28.    scanf("%s",a);
  29.    while(true) {
  30.       scanf("%s", b);
  31.       if(strcmp(b, "0") == 0) break;
  32.       sum(a, b, c);
  33.       p = c;
  34.       if(*== '0') p++;
  35.       strcpy(a, p);
  36.    }
  37.    
  38.    printf("The result is: %s \n", a);
  39.    system("pause");
  40.    return 0;
  41. }

猜你喜欢

转载自blog.csdn.net/qiangshuting/article/details/80471163