我的简单求幂代码不起作用?

问题描述 投票:0回答:1

我的代码返回此错误:

错误! 未处理的异常: 堆栈溢出异常 [错误] 致命的未处理异常:System.StackOverflowException:请求的操作导致堆栈溢出。 在 HelloWorld.x (System.Int32 y) <0x41e36180 + 0x00004> 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中
[...]
<0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0x00001] 中 <0e1357c43db845f2b6acb041d1724d28>:0 在 HelloWorld.x (System.Int32 y) [0 等...

我发誓什么都试过了,但没有任何效果。

我的代码:

using System;

public class HelloWorld

{
    static int x(int y)
    {
        return x(y)*x(y)+y;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine (x(1));
    }
}
c#
1个回答
-1
投票

解决问题,我们需要知道这是什么应该表现得像。

至于什么原因导致异常

  1. 你没有停止条件。
  2. 您将未更改的输入传递到下一个递归步骤。

其中每一个都足以让递归无限运行(理论上 - 实际上,直到你耗尽内存,即堆栈溢出 - 因此“StackOverflowException”)。

© www.soinside.com 2019 - 2024. All rights reserved.