从语法上讲,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# 应用程序中对此提供了非常丰富的支持。您可以观察函数如何递归调用自身,观察每一行按顺序执行,甚至可以看到变量的值随着对它们执行操作而发生变化。