在C中添加大整数[重复]

问题描述 投票:1回答:2

这是一个非常简单的问题:

如何获得2个无符号整数值并将其添加到C中以用于以下输入约束。

0 <= A,B <= 10 ^ 98

我知道我可以将输入内容当作字符串,但我仍牢记着这个问题。

我已经写了下面的代码,但是它不能取10 ^ 98这样大的值

#include <stdio.h>

int main() {
    unsigned long long int a, b;
    int x = scanf("%llu%llu", &a, &b);
    while (x > 0) {
        printf("%llu\n",(a + b));
        x = scanf("%llu%llu" ,&a, &b);
    }
    return 0;
}
c long-integer biginteger unsigned-integer
2个回答
1
投票

您不能为此使用常规的算术类型,即使unsigned long long仅具有64位,这比您的目的所需的位数要少得多。

还请注意,您的循环测试不正确:应该为while (x == 2)

这里是一个小程序,可以处理99位十进制数字:

#include <stdio.h>
#include <string.h>

char *bigadd(char *c, const char *a, const char *b) {
    size_t alen = strlen(a);
    size_t blen = strlen(b);
    size_t clen = (alen > blen) ? alen : blen;
    size_t i = clen;
    int digit, carry = 0;
    c[i] = '\0';
    while (i > 0) {
        digit = ((alen ? a[--alen] - '0' : 0) +
                 (blen ? b[--blen] - '0' : 0) +
                 carry);
        carry = digit >= 10;
        c[--i] = (char)('0' + (digit - carry * 10));
    }
    if (carry) {
        memmove(c + 1, c, clen + 1);
        c[0] = '1';
    }
    return c;
}

int main(int argc, char *argv[]) {
    char a[100], b[100], c[101];

    while (scanf("%99s%99s", a, b) == 2) {
        printf("%s\n", bigadd(c, a, b));
    }
    return 0;
}

0
投票

尝试使用bignum库,例如GMP。这是一个例子。

#include <gmp.h>
#include <stdio.h>
#include <assert.h>

int main(){

  char inputStr[1024];
  /*
     mpz_t is the type defined for GMP integers.
     It is a pointer to the internals of the GMP integer data structure
   */
  mpz_t n;
  int flag;

  printf ("Enter your number: ");
  scanf("%1023s" , inputStr); /* NOTE: never every write a call scanf ("%s", inputStr);
                                  You are leaving a security hole in your code. */

  /* 1. Initialize the number */
  mpz_init(n);
  mpz_set_ui(n,0);

  /* 2. Parse the input string as a base 10 number */
  flag = mpz_set_str(n,inputStr, 10);
  assert (flag == 0); /* If flag is not 0 then the operation failed */

  /* Print n */
  printf ("n = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");

  /* 3. Add one to the number */

  mpz_add_ui(n,n,1); /* n = n + 1 */

  /* 4. Print the result */

  printf (" n +1 = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");


  /* 5. Square n+1 */

  mpz_mul(n,n,n); /* n = n * n */


  printf (" (n +1)^2 = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");


  /* 6. Clean up the mpz_t handles or else we will leak memory */
  mpz_clear(n);

}
© www.soinside.com 2019 - 2024. All rights reserved.