简体   繁体   English

通过递归的幂函数

[英]Power function by means of recursion

The implementation should compute a number to the nth power using recursion, however, every call to itself, keeps "nb" unchanged, while power decrements.实现应该使用递归计算一个数的 n 次方,但是,每次调用自身时,“nb”保持不变,而功率递减。 I've tried using a accumulator variable but this reinitializes to default with every repeated call.我试过使用累加器变量,但是每次重复调用都会重新初始化为默认值。 Is there a way to save nb * nb to nb, without adding an extra parameter?有没有办法将 nb * nb 保存到 nb,而不添加额外的参数? or losing the base value?或失去基础价值?

When I run ft_recursive_power(3, 10);当我运行 ft_recursive_power(3, 10); in ac visualizer (ctutor) and pass it these arguments, it displays that nb remains 3 throughout the execution, and returns 177147, while it should accumulate the multiplication and return 59049. Or am I missing something?在 ac 可视化器 (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);
}

You're getting an incorrect result because your base case is wrong.您得到的结果不正确,因为您的基本情况是错误的。

The value 177147 is 3 11 as opposed to 3 10 , which means you're multiplying one extra time.值 177147 是 3 11而不是 3 10 ,这意味着您要多乘一次。 That happens because you return nb in the base case when power is 0.发生这种情况是因为当power为 0 时,您在基本情况下return nb

When raising a number to the 0 power the result is 1, so your base case should be 1.当将一个数字提高到 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;
}

Here your problem:你的问题在这里:

if (power == 0 && nb == 0)

should be replaced by应该替换为

if (power == 0)

and added case (nb == 0) as well并添加了 case (nb == 0) 以及

if (nb == 0)如果(nb == 0)

The function should work for negative power as well, so I suggested change the return type to float.该函数也应该适用于负功率,所以我建议将返回类型更改为浮动。

It is my solution:这是我的解决方案:

float   ft_recursive_power(int nb, int power)
{
    // 0 to the 0th case
    if (power == 0)
        return 1;
    if (nb == 0)
        return 0;

    // recursive case
    // power is positive
    if (power > 0)
        return (nb * ft_recursive_power(nb, power - 1));

    // mean power is negative
    else
        return (ft_recursive_power(nb, power + 1) / nb);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM