所以这显然是一段有效的代码,但我不知道如果 exponent
参数是任何东西,第二次调用 power
是如何完成的除了 0
。
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
请您参考如下方法:
因为第二次调用会一直调用指数中较小的数字,直到达到0,然后返回1,并回滚聚合结果...
我认为你必须阅读一些递归知识 :)
这是一个简单的例子:
power(2,2)
power(2,1)
power(2,0)
return 1
return 2*1 = 2
return 2*2 = 4
取自并修改自 page .
试试这个页面 an animated view of the recursion (对我不起作用,这是一个旧页面,需要 java,但我的机器上没有安装它...)
编辑:
令我困扰的是我找不到任何简单的例子,所以这里有一个快速的控制台程序,可以帮助您直观地了解它是如何工作的:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SO_Console
{
class Program
{
static void Main(string[] args)
{
int base_value = 0;
int exponent = 0;
string[] parts = new string[2];
int result = 0;
Console.Out.WriteLine("Please enter the Power to calculate in this format: x^y "
+ Environment.NewLine + "(where x is the base (int) and y is the exponent (int)."
+ Environment.NewLine);
var temp = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(temp))
{
parts = temp.Split('^');
if (parts.Length != 2)
InvalidInput();
}
else
InvalidInput();
if (Int32.TryParse(parts[0], out base_value) && Int32.TryParse(parts[1], out exponent))
result = Power(base_value, exponent, "");
else
InvalidInput();
Console.Out.WriteLine(Environment.NewLine + "Final result = {0}", result);
Console.Out.WriteLine(Environment.NewLine + "Hit any key to quit.");
Console.Read();
}
/// <summary>
/// Recursive call to calculate Power x^y
/// </summary>
/// <param name="base_value">The base</param>
/// <param name="exponent">The exponent</param>
/// <param name="padding">Padding, for output.</param>
/// <returns></returns>
private static int Power(int base_value, int exponent, string padding)
{
Console.Out.WriteLine(string.Format("{2}Power called with: {0}^{1}", base_value, exponent, padding));
Thread.Sleep(750);
if (exponent == 0)
{
Console.Out.WriteLine("{0}{1}Base case reached, returning 1.{0}", Environment.NewLine ,padding);
return 1;
}
else
{
var return_value = base_value * Power(base_value, exponent - 1, padding + " ");
Console.Out.WriteLine("{0}Going back in the recursion, returning {1}.", padding, return_value);
Thread.Sleep(750);
return return_value;
}
}
/// <summary>
/// Inform user about bad input and quit.
/// </summary>
private static void InvalidInput()
{
Console.Out.WriteLine("Invalid input.");
return;
}
}
}
您只需粘贴并运行它,您的结果就会看起来像:
编辑 2:
我已经写了一篇关于这个的文章,详细解释了发生了什么,为什么在哪里。欢迎您在这里查看:simple power recursion, console application .