1

提前感谢您查看此内容。

当我尝试运行我在 Code::Blocks 中用 C 语言编写的这个程序时,我收到一条 Windows 错误消息。有趣的是它编译得很好,如果我降低我正在测试的上限,程序也运行得很好。

细节:

当我尝试运行该程序时,首先我得到一个 Windows 弹出窗口,上面写着“X.exe 已停止工作。Windows 正在检查问题的解决方案”。很快,这将更改为“X.exe 已停止工作。一个问题导致程序停止正常工作。Windows 将关闭该程序并通知您是否有可用的解决方案。(关闭程序)”我单击关闭程序按钮,然后我看到命令提示符显示“进程返回 255 <0xFF> 执行时间 3.940 秒按任意键继续”。

我有 Windows 8。

我正在使用 GNU GCC 编译器。

如果我将“最高”更改为 100000,则程序运行良好。

这是代码:

/************************************************
* Finds the starting integer under 1000000 that
* produces the longest Collatz sequence, and the
* length of said sequence.
*************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <limits.h>
#define upto 1000000

int main()
{
    long i;
    long long j;
    long long max = LONG_LONG_MAX;
    long length = 0;
    long number = 0;
    long penull = 0;
    long len[upto];
    for (i = 0; i < upto; i++) (len[i] = 0);
    // counts length of Collatz sequence for starting integers from 1 to 999999
    for (i = 1; i < upto; i++)
    {
        j = i;
        while (j != 1)
        {
            assert (j <= (max - 1)/3);
            if (j%2 == 0) (j = j/2);
            else (j = 3*j + 1);
            len[i]++;
            if (j < i)
            {
                len[i] = len[i] + len[j];
                j = 1;
            }
        }
        // stores length of the longest sequence and the starting integer producing it
        if (len[i] > length)
            {
                length = len[i];
                number = i;
            }
        // stores a duplicate length for later comparison
        else if (len[i] == length) (penull = len[i]);
    }
    if (length == penull) (printf("There are at least two!"));
    else printf("%ld produces a Collatz sequence of length %ld", number, length + 1);
    return 0;
}
4

1 回答 1

0

将数组移到函数lenmain。堆栈的大小有时是有限的,局部变量存储在堆栈上。通过将其移到外部,您可以使其成为全局变量。

于 2013-11-08T21:06:21.763 回答