在C中存储较大的整数值

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

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

如何获得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
1个回答
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.