gpt4 book ai didi

c - 为什么这个 C 程序在 windows 上崩溃而在 linux 上运行正常?

转载 作者:可可西里 更新时间:2023-11-01 11:26:46 25 4
gpt4 key购买 nike

我写了一个程序来求谐波数

(the n-th harmonic number is the sum of the reciprocals of the first n natural numbers)

数字序列。我的程序将其输入作为命令行参数并以表格格式打印谐波数。作为一个例子,它是这样工作的:

 C:\Users\EDDiE\c>har 10 30 5
10 2.9289682539682538
15 3.3182289932289937
20 3.5977396571436819
25 3.8159581777535068
30 3.9949871309203906

10(argv [1]) = starting number,

30(argv[2]) = ending number,

5(argv[3]) = step to advance.

我的windows 8机器上这个程序崩溃编号43429

然后我在 an online c compiler 上执行这是一个 linux 环境(“我认为”,我不是 linux 用户)然后它工作正常。

这是我的程序:

har.c

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

double harmonic(int);

int main(int argc, char *argv[])
{

int j;
int start = 1, end = 10, step = 1;

switch(argc) {
case 1:
break;
case 2:
end = atoi(argv[1]);
break;
case 3:
start = atoi(argv[1]);
end = atoi(argv[2]);
break;
case 4:
start = atoi(argv[1]);
end = atoi(argv[2]);
step = atoi(argv[3]);
break;
}

for (j = start; j <= end; j += step)
printf("%7d %3.20g\n", j, harmonic(j));

return 0;
}


double harmonic(int n)
{
//double H;
if (n == 1 || n == 0)
return 1.0;
else
return (1.0 / (double) n) + harmonic(n - 1);

//return H;
}

我需要知道为什么这个程序在 windows 环境下崩溃。

我需要在代码(或我的系统)中修改什么吗?

最佳答案

正如评论中所述,您很可能正在经历堆栈溢出。不过还是有希望的,您的递归可以很容易地转换为迭代,如下所示:

double harmonic(int n) {
if(n == 0) return 1.0;
double res = 0.0;
while(n > 0) {
res += (1.0 / (double) n);
--n;
}
return res;
}

这样你的程序将适用于大的n

关于c - 为什么这个 C 程序在 windows 上崩溃而在 linux 上运行正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515746/

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