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

Why is this C program crashes on windows and works fine on linux?

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

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

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

 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.

我的windows8机器这个程序崩溃号码43429

然后我在 an online c compiler 上执行它是一个 linux 环境("I think",我不是 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