首页 > 解决方案 > 递归的幂函数

问题描述

实现应该使用递归计算一个数字的 n 次方,但是,每次调用自身时,都会保持“nb”不变,而幂会递减。我试过使用累加器变量,但是每次重复调用都会重新初始化为默认值。有没有办法将nb * nb保存到nb,而不添加额外的参数?或失去基本价值?

当我运行 ft_recursive_power(3, 10); 在 ac Visualizer (ctutor) 中并将这些参数传递给它,它显示 nb 在整个执行过程中保持 3,并返回 177147,而它应该累积乘法并返回 59049。或者我错过了什么?

int   ft_recursive_power(int nb, int power)
{
  // 0 to the 0th case
  if (power == 0 && nb == 0)
    return (1);
  // recursive case
  if (power > 0)
    return (nb * ft_recursive_power(nb, power - 1));
  return (nb);
}

标签: crecursionmathexponent

解决方案


你得到一个不正确的结果,因为你的基本情况是错误的。

值 177147 是 3 11而不是 3 10,这意味着您要增加一个额外的时间。发生这种情况是因为您return nb在基本情况下 whenpower是 0。

将数字提高到 0 次方时,结果为 1,因此您的基本情况应为 1。

int   ft_recursive_power(int nb, int power)
{
  // 0 to the 0th case
  if (power == 0 && nb == 0)
    return 1;
  // recursive case
  if (power > 0)
    return nb * ft_recursive_power(nb, power - 1);
  return 1;
}

推荐阅读