c语言 高精度运算

核心思想为用字符串标识数字的每一位,并模拟c语言的底层运算

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

char a[100000] = { 0 }, b[100000] = { 0 }, c[100000] = { 0 };

int main()
{
    char help[10] = { 0 };
    int i, j, k, len;
    int n;
    printf("input:\n");
    scanf("%d", &n);

    len = 1;
    b[0] = 1;
    for (i = 1; i <= n; i++)
    {
        _itoa(i, help, 10);
        for (j = 0; j < strlen(help); j++)
        {
            a[j] = help[j] - '0';
        }

        for (j = 0; j < len; j++)
        {
            for (k = 0; k < strlen(help); k++)
            {
                c[j + k] += a[k] * b[j];
                c[j + k + 1] += c[j + k] / 10;
                c[j + k] %= 10;
            }
        }

        if (c[j + k - 1] != 0)
        {
            len = j + k;
        }
        else
        {
            len = j + k - 1;
        }

        memcpy(b, c, sizeof(b));
        memset(c, 0, sizeof(c));
    }

    for (i = len - 1; i >= 0; i--)
        printf("%d", b[i]);
    printf("\nlen: %d", len);
}
posted @ 2022-08-02 16:26  bitterteaer  阅读(179)  评论(0编辑  收藏  举报