如何将两个 25 位数字相加?

0 c types biginteger long-integer

我正在尝试在 C 中添加大约 25 位数字。我得到的结果与预期的、可能的原因数据类型有点不同。

/* Online C Compiler and Editor */
#include <stdio.h>

int main()
{
    long double result;
    long double a;
    long double b;
    a = 51680708854858333333;
    b = 83621143489848333333,
    result = a + b;
    printf("Hello, World!\n");
    printf("can be written %.0Lf\n", result);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*hil 6

你可以按照小学教的方法来做:

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


/*  Add two numbers represented by strings of digit characters.  The result is
    returned in dynamically allocated memory, which the caller is responsible
    for freeing.  The strings are not tested to ensure they contain only
    digits.

    The result may contain a leading zero.  This could be eliminated by testing
    after the addition, shifting all the characters left one space, and
    reallocating if desired.
*/
static char *add(const char *a, const char *b)
{
    //  Measure lengths of strings.
    size_t la = strlen(a);
    size_t lb = strlen(b);

    //  Plan space for result, allowing an extra character in case of carry.
    size_t lc = (la < lb ? lb : la) + 1;

    //  Allocate space for result digits plus a terminating null character.
    char *c = malloc(lc+1);
    if (!c)
    {
        fprintf(stderr, "Error, unable to allocate %zu bytes for sum.\n", lc+1);
        exit(EXIT_FAILURE);
    }
    c[lc] = '\0';

    /*  Add digits from right to left.  i counts positions from the right of
        the numerals.
    */
    int carry = 0;
    for (size_t i = 0; i < lc; ++i)
    {
        /*  Get digit from each addend.  While i is within a numeral, get its
            digit character and subtract '0' to convert it from a digit
            character ('0' to '9') to a plain number (0 to 9).  When i is
            outside the numeral, use zero.
        */
        int da = i < la ? a[la-1-i] - '0' : 0;
        int db = i < lb ? b[lb-1-i] - '0' : 0;
        
        /*  Add the digits, record the low digit of the sum in c, and calculate
            the carry to the next column.  The digit for c is converted from a
            plain number to a digit character.
        */
        int sum = da + db + carry;
        c[lc-1-i] = sum % 10 + '0';
        carry = sum/10;
    }

    return c;
}


int main(void)
{
    const char a[] = "51680708854858333333";
    const char b[] = "83621143489848333333";

    char *c = add(a, b);
    
    printf("sum = %s.\n", c);

    free(c);
}
Run Code Online (Sandbox Code Playgroud)