c - 递归的幂函数
问题描述
实现应该使用递归计算一个数字的 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);
}
解决方案
你得到一个不正确的结果,因为你的基本情况是错误的。
值 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;
}
推荐阅读
- html - CSS;- Radio buttons with circles having very less spacing between them
- docker - TensorFlow Docker -- Cannot find mounted drive
- r - match values with different dates data.table
- sql - Athena SQL 复合回报
- tfs - In TFS 2017 can you execute all phases on the same agent?
- spring - 在 Spring Boot 中加载上下文之前启动嵌入式服务器以进行测试
- text - How to select from line to line in vi?
- python-3.x - 在csv文件中写入多行
- python - Python Using Recursion to Traverse Through a Nested List With Conditions
- django - How to add multiple form field types of choices for a question in django?