gpt4 book ai didi

c# - 段错误 : 11

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:15 25 4
gpt4 key购买 nike

我正在完成一个非常简单的 programming excersize使用以下代码:

    using System;

namespace Factorial

{
class MainClass
{

static int fives(int x) {

int r = 0;
while(x % 5 == 0) {
r++;
x /= 5;
}
return r;

}

static int z(int x) {

if (x == 1)
return 0;
else
return z (x-1) + fives (x);

}

public static void Main (string[] args)
{
int testCases = Convert.ToInt32 (Console.ReadLine ());
int[] xs = new int[testCases];
for (int i=0; i<testCases; i++)
xs [i] = Convert.ToInt32 (Console.ReadLine ());
foreach (int x in xs)
Console.WriteLine (z (x));
}
}
}

它似乎适用于小数字,但使用示例中的 8735373 打印“段错误:11”。这是否意味着由于递归太深而导致内存不足?是什么原因造成的?

(我在 Mac 上的 Mono 2.10.8 中运行 C#。)

P.S.:如果有人对 excersize 本身感兴趣, here's my final solution (更优化)。

最佳答案

这看起来像是未处理的 StackOverflowException - 过度使用递归时很常见。所以......不要过度使用递归。对于数学和一些非常特定的语言可能很好(F# 可能会应付),但 C#... 不是那么多。

看起来像(未验证):

    static int z(int x)
{
int accumulator = 0;
while(x!=1)
{
accumulator += fives(x);
x--;
}
return accumulator;
}

这不会出错 - 它不会递归(尽管每次迭代都会调用 fives)。更好的是:做代数找到直接公式。

关于c# - 段错误 : 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10807059/

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