gpt4 book ai didi

c - 如何对大数求和

转载 作者:行者123 更新时间:2023-11-30 18:53:01 27 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序可以对非常大的数字进行求和。不幸的是我被困住了 - 即使我注释掉 malloc 和 realloc (编译器似乎失败),它也不会返回任何结果。有任何想法吗?我的代码:

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

int i,j,x;
char *actual = NULL;
char *sum = NULL;

void init () {
sum = malloc(500);
actual = malloc(500);
}

void calculate (char *argv[]) {
int rest = 0;
actual = *argv;
actual = realloc(actual, strlen(*argv));
if (strlen(actual) > strlen(sum)) {
sum = realloc(sum, strlen(actual) + 1);
} else sum = realloc(sum, strlen(sum) + 1);
long b;
for (b = 1; b < strlen(actual); b++) {
rest = rest + atoi(&sum[strlen(sum) - b]) + atoi(&actual[strlen(actual) - b]);
if (rest > 9) {
sum[strlen(sum) - b] = rest - 10;
rest = 1; // carrying over 1
} else {
sum[strlen(sum) - b] = rest;
rest = 0;
}
}
}

void writeResult () {
printf("VYPIS - sum:");
printf("strlen souctu je: %lu\n",strlen(sum));
long c;
for (c = 0; c <= strlen(sum); c++) {
printf("%c",sum[c]);
}
printf("\n");
}

void emtpy () {
free(actual);
free(sum);
}

int main(int argc, char * argv[]) {
init();
for (i = 1; i < argc; i++) {
calculate(&argv[i]);
}
writeResult();
emtpy();
return 0;
}

最佳答案

尝试realloc argv是未定义的行为。一般来说,您不应该reallocmalloc-ed或从显式将内存所有权转移给您的函数接收的内容。

另请注意,atoi 需要一个以 null 结尾的 C 字符串,因此向其传递长字符串的一部分是不正确的。如果您想获取 char 数字的数值,请减去 '0',如下所示:

int digit = actual[strlen(actual) - b] -'0';

要将单个十进制数字转换为 char,请添加 '0':

res[b] = digit + '0';

关于c - 如何对大数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33721898/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com