在c#中使用递归方法时遇到问题

本文关键字:遇到 问题 递归方法 | 更新日期: 2023-09-27 18:28:56

在c#中使用递归方法时遇到问题。编译时,它应该只显示给定int的所有数字的总和sumUpToo,即-输入10-输出55(10+9+8+7+6+5+4+3+2+1+0)

我在任何地方都找不到任何信息,所以如果有人能链接到一个网站,教我如何浏览它,我将不胜感激。

class Program
{
    static void Main(string[] args)
    {
        public static int sum(int x)
        {
        Console.WriteLine("num");
        x = Console.ReadLine();
        int sum = 0, i = 0;
        for (i = 0; i <= x; i++)
        {
            sum = sum + i;
        }
        Console.WriteLine("{0}", sum);
        }
        public static int recursivesum(int x)
        {
        if (x <= 1)
            Console.WriteLine("{0}", x);
        else
           (x + Recursivesum(x - 1));
        }

编辑:如果我没有弄错的话,这个调整现在似乎很好。感谢的所有帮助

class Program
{
    static void Main(string[] args)
    {
        int x;
        Console.Write("Please enter an integer value to sum up to: ");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("The sum of all numbers up to and including {0} is {1}",x, recursivesum(x));
    }
    public static int sum(int x)
    {
        int sum = 0, i = 0;
        for (i = 0; i <= x; i++)
        {
        sum = sum + i;
        }
        return sum;
    }
    public static int recursivesum(int x)
    {
        if (x <= 1)
            return x;    
        else
            return x + recursivesum(x-1);
    }
}

}

在c#中使用递归方法时遇到问题

初学者经常遇到递归函数的问题。严格遵循这个模式,你就不太可能出错:

ReturnType RecursiveFunction(ArgumentType argument)
{
    if (the argument is such that the problem can be trivially solved)
        return the trivial solution;
    // The problem could not be trivially solved. 
    // Break it down into one or more smaller problems.
    ArgumentType smallerProblemArgument = whatever;
    ReturnType smallerProblemSolution = RecursiveFunction(smallerProblemArgument);
    // We have solved the smaller problem.
    ReturnType bigProblemSolution = ...
    // ... use the smaller problem solution to solve the bigger problem...
    return bigProblemSolution;
}

所以在你的情况下:

public static int SumOfFirstNIntegers(int n)
{
    if (n <= 0) // trivial case
        return 0;
    // We have a harder problem to solve. Make the problem simpler:
    int smallerProblem = n-1;
    int smallerSolution = SumOfFirstNIntegers(smallerProblem);
    // We have solved the smaller problem. Use it to solve the big problem.
    int bigSolution = smallerSolution + n;
    return bigSolution;
}

递归函数是一个调用它self的函数。您需要一个将退出函数的基本情况,以及一个递归情况,其中函数使用修改的参数调用自己。你的功能应该是这样的:

public static int recursivesum(int x)
{
    if (x <= 1)
        return x;    // this is the base case
    else
        return x + recursivesum(x-1);
}

所以要使用这个函数,你只需这样称呼它:

recursivesum(10);

如果你遵循函数的逻辑,你会看到它将返回10+递归和(9)。递归和(9)将返回9+递归和(8)。现在我们有10+9+递归和(8)。

这将一直持续到我们达到10+9+8+7+6+5+4+3+2+递归和(1)的点。现在,如果你再看一下这个函数,递归和(1)就不会再调用它自己了。相反,它只返回x。所以现在函数将展开,您将得到您期望的结果。

关于递归的最后一点说明。递归可以是实现某些算法的一种非常优雅的方式,但它也有危险。这个网站不是无缘无故地被称为堆栈溢出!