递归循环 (C#)

发布于 2024-11-03 06:10:14 字数 509 浏览 1 评论 0 原文

有人可以向我解释一下吗?我在 C# 中编写了一个函数来计算这样的数字的阶乘:

public int factorial(int input)
{
    if (input == 0 || input == 1)
        return 1;
else
{
    int temp = 1;
    for (int i = 1; i <= input; i++)
        temp = temp * i;
    return temp;
    }
}

但是我发现了一些 C++ 代码(我真的不知道任何 C++ 顺便说一句),它使用递归循环查找阶乘:

int factorial(int number) {
 int temp;
 if(number <= 1) return 1;
 temp = number * factorial(number - 1);
 return temp;
}

有人可以向我解释它是如何工作的吗?谢谢。

Can someone please explain it to me? I wrote a function to calculate the factorial of a number like this in C#:

public int factorial(int input)
{
    if (input == 0 || input == 1)
        return 1;
else
{
    int temp = 1;
    for (int i = 1; i <= input; i++)
        temp = temp * i;
    return temp;
    }
}

But I found some C++ code (I don't really know any C++ btw) which finds a factorial using a recursive loop:

int factorial(int number) {
 int temp;
 if(number <= 1) return 1;
 temp = number * factorial(number - 1);
 return temp;
}

Can someone explain to me how it works? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不喜欢何必死缠烂打 2024-11-10 06:10:14

嗯,它使用了以下事实:factorial(n)n * Factorial(n - 1),基本情况为 n = 1

例如:

factorial(5) = 5 * factorial(4)
             = 5 * 4 * factorial(3)
             = 5 * 4 * 3 * factorial(2)
             = 5 * 4 * 3 * 2 * factorial(1)
             = 5 * 4 * 3 * 2 * 1

实现仅使用此递归定义。

Well, it uses the fact that factorial(n) is n * factorial(n - 1) with a base case of n = 1.

So for example:

factorial(5) = 5 * factorial(4)
             = 5 * 4 * factorial(3)
             = 5 * 4 * 3 * factorial(2)
             = 5 * 4 * 3 * 2 * factorial(1)
             = 5 * 4 * 3 * 2 * 1

The implementation just uses this recursive definition.

柠北森屋 2024-11-10 06:10:14

从语法上来说,C++ 代码与用 C# 编写的代码相同。不要让语言差异让您措手不及!对我来说,它实际上看起来像 C,因为变量是在函数顶部声明的;这在 C++ 或 C# 中都不是绝对必要的。我更喜欢在第一次使用变量时声明它们,将声明和初始化结合在一个语句中,但这只是一种风格偏好,不会改变代码的功能。

我将尝试通过向代码片段的每一行添加注释来解释这一点:

// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
    // Declare a temporary variable of type integer
    int temp;

    // This is a guard clause that returns from the function immediately
    // if the value of the argument is less than or equal to 1.
    // In that case, it simply returns a value of 1.
    // (This is important to prevent the function from recursively calling itself
    // forever, producing an infinite loop!)
    if(number <= 1) return 1;

    // Set the value of the temp variable equal to the value of the argument
    // multiplied by a recursive call to the Factorial function
    temp = number * Factorial(number - 1);

    // Return the value of the temporary variable
   return temp;
}

递归调用 只是意味着该函数从同一函数内调用自身。这是可行的,因为 n 的阶乘相当于以下语句:

n! = n * (n-1)! 

理解代码如何工作的一种很好方法是将其添加到测试项目中,然后使用调试器单步执行代码。 Visual Studio 在 C# 应用程序中对此提供了非常丰富的支持。您可以观察函数如何递归调用自身,观察每一行按顺序执行,甚至可以看到变量的值在对其执行操作时发生变化。

Syntactically, the C++ code is identical to the same code written in C#. Don't let the language discrepancy catch you off guard! It actually looks like C to me, given that the variable is declared at the top of the function; that's not strictly necessary in either C++ or C#. I prefer to declare variables the first time I use them, combining the declaration and initialization in one single statement, but that's merely a stylistic preference that doesn't change the function of the code.

I'll try to explain this by adding comments to each line of the code snippet:

// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
    // Declare a temporary variable of type integer
    int temp;

    // This is a guard clause that returns from the function immediately
    // if the value of the argument is less than or equal to 1.
    // In that case, it simply returns a value of 1.
    // (This is important to prevent the function from recursively calling itself
    // forever, producing an infinite loop!)
    if(number <= 1) return 1;

    // Set the value of the temp variable equal to the value of the argument
    // multiplied by a recursive call to the Factorial function
    temp = number * Factorial(number - 1);

    // Return the value of the temporary variable
   return temp;
}

Recursive calls simply mean that the function calls itself from within the same function. This works because the factorial of n is equivalent to the following statement:

n! = n * (n-1)! 

One great way to understand how code works is to add it to a test project, then single-step through the code using the debugger. Visual Studio has very rich support for this in C# applications. You can watch how the function recursively calls itself, watching each line execute in sequence, and even seeing the values of the variables change as operations are performed on them.

一城柳絮吹成雪 2024-11-10 06:10:14

让我们逐行分析一下:

if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;

第 1 行:如果数字小于或等于 0,则返回 1。这就是说 0! = 11! = 1

第 2 + 3 行:否则我们返回 number * Factorial(number - 1)。让我们看看 5! (为了简洁起见,我使用 n! 作为 factorial(n) 的同义词)

5!
5 * 4!
5 * 4 * 3!
5 * 4 * 3 * 2!
5 * 4 * 3 * 2 * 1!
5 * 4 * 3 * 3 * 1 // Here we don't have to expand 1! in the same way because of the condition

所以整个事情展开了出去。 的属性

它只是使用n! 。 = n * (n - 1) * ... * 2 * 1 = n * (n - 1)!

警告:与往常一样,递归代码将遭受堆栈溢出和内存使用量增加的问题迭代(或尾递归优化)版本,因此使用风险自负。

Lets analyze this line by line:

if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;

Line 1: If the number is less than or equal to zero, we return 1. This is saying that 0! = 1 and 1! = 1

Lines 2 + 3: Otherwise we return number * factorial(number - 1). Lets look at this for 5! (here i use n! as a synonym for factorial(n) for brevity)

5!
5 * 4!
5 * 4 * 3!
5 * 4 * 3 * 2!
5 * 4 * 3 * 2 * 1!
5 * 4 * 3 * 3 * 1 // Here we don't have to expand 1! in the same way because of the condition

So the whole thing expands out. Its just using the property that

n! = n * (n - 1) * ... * 2 * 1 = n * (n - 1)!

Warning: The recursive code, as always, will suffer from a stack overflow and increased memory usage as compared to an iterative (or tail-recursive-optimized) version, so use at your own risk.

陈年往事 2024-11-10 06:10:14

递归函数是在函数体中调用自身的函数。为了使其有界并最终返回一个值,必须发生两件事:

  1. 它必须有一个基本情况,在该情况下它不会再次调用自身并返回已知值。此基本情况停止递归。对于阶乘函数,当输入为 0 时,该值为 1。

  2. 其递归应用必须收敛到基本情况。对于阶乘,递归应用程序调用输入减 1 的函数,最终将收敛到基本情况。

查看此函数的一种更简单的方法是(仅对正输入有效):

int factorial(int input) {
  return input == 0 ? 1 : input * factorial(input - 1);
}

A recursive function is a function that calls itself in its body. For it be bounded, and eventually return a value, two things must happen:

  1. It has to have a base case where it doesn't call itself again, returning a known value. This base case stops the recursion. For the factorial function, this value is 1 when the input is 0.

  2. Its recursive applications must converge to the base case. For factorial, the recursive application calls the function with the input subtracted by 1, which will eventually converge to the base case.

A simpler way to look at this function is this (only valid for positive input):

int factorial(int input) {
  return input == 0 ? 1 : input * factorial(input - 1);
}
慈悲佛祖 2024-11-10 06:10:14

递归函数是从同一个函数调用的函数,

例如:

  Test()
    {
      i++;
      Test();
      cout<<i;
    }

查看代码,它将一次又一次地调用该函数。

递归问题,它将无限工作,因此想通过特定条件停止它,

上面代码中的一些更改现在看起来

int i=0; 
Test()
        {
         if(i==10) return;
         i++;
         Test();
         cout<<i;
        }

输出将是 10打印10次,这里这行cout<将在return后执行

Recursive function are function calling from the same function

eg:

  Test()
    {
      i++;
      Test();
      cout<<i;
    }

look at the code it will call the function again and again

Problem with recursion it will work infinitely so want to stop it by a particular condition

some change in above code now look

int i=0; 
Test()
        {
         if(i==10) return;
         i++;
         Test();
         cout<<i;
        }

output will be 10 printed 10 times, here this line cout<<i; will execute after return

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文