[英]C program recursive function
I have a small problem I want to build a function that returns with recursive function the n n expression with one parameter in the calling function. 我有一个小问题,我想构建一个函数,该函数以递归函数的形式在调用函数中返回带有一个参数的n n表达式。 Can someone help me?
有人能帮我吗? My thought so far :
到目前为止,我的想法是:
int powerThroughRecursion(int n) {
if (n == 0) {
return 1;
}
if (n <= 1) {
return n;
}
return n * powerThroughRecursion(n - 1);
}
Yes, you are actually computing n!
是的,您实际上正在计算
n!
there. 那里。 One way to do it is the following:
一种实现方法如下:
#include <iostream>
#include <string>
int powerThroughRecusion(int n, int step) {
if (step < 1)
return 1;
return n * powerThroughRecusion(n, step - 1);
}
int main()
{
std::cout << powerThroughRecusion(4, 4);
}
You multiply by n, but a step will tell you how much multiplications to be done. 您乘以n,但是一个步骤将告诉您要进行多少次乘法。
[edit] using a single parameter function [编辑]使用单个参数功能
#include <iostream>
#include <string>
int powerThroughRecusionInternal(int n, int step) {
if (step < 1)
return 1;
return n * powerThroughRecusionInternal(n, step - 1);
}
int powerThroughRecusion(int n)
{
return powerThroughRecusionInternal(n, n);
}
int main()
{
std::cout << powerThroughRecusion(2) << "\n";
std::cout << powerThroughRecusion(4);
}
If you want a one parameter function. 如果要一个参数功能。 just hide and wrap the two parameter implementation version with another function call.
只需用另一个函数调用隐藏和包装两个参数的实现版本即可。
static int powerThroughRecusionImpl(int n, int power) {
if (power == 0) {
return 1;
}
if (power == 1) {
return n;
}
return n * powerThroughRecusionImpl(n ,power - 1);
}
int powerThroughRecusion(int n) {
return powerThroughRecusionImpl(n ,n);
}
Or if you want to be non thread-safe. 或者,如果您想成为非线程安全的。
int powerThroughRecusion(int n) {
static int base = 0;
if (!base) {
base = n;
n = powerThroughRecusion(n);
base = 0;
return n;
} else {
if (n == 0) {
return 1;
} else if (n == 1) {
return base;
}
return base * powerThroughRecusion(n - 1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.