C++ 递归计算函数f=n的值/(c^n)
在上周的一次测试中,我被问到了这个问题:C++ 递归计算函数f=n的值/(c^n),c++,recursion,C++,Recursion,在上周的一次测试中,我被问到了这个问题: /* Task 1: Implement the following function for calculating the value of the function f = n!/(c^n). */ float func(int n, int c) { } 我现在正试图在事后找出答案,因为这是我在测试中无法解决的问题(递归是我难以解决的问题) 这是我迄今为止的尝试: float result = 0; // n!*c^n-1
/* Task 1: Implement the following function for calculating the value of
the function f = n!/(c^n).
*/
float func(int n, int c) {
}
我现在正试图在事后找出答案,因为这是我在测试中无法解决的问题(递归是我难以解决的问题)
这是我迄今为止的尝试:
float result = 0;
// n!*c^n-1
float func( int n, int c )
{
if( n == 0 )
return result;
result += n*c;
return func( n*n-1, pow(c,-n) );
}
如果有人能帮我解决这个问题,我将不胜感激。谢谢大家
float result = 1;
// n!*c^n-1
float func( double n, double c )
{
if( n == 0 )
return result;
return func(n-1,c )*(n/c);
}
这是用来解决这个问题的算法
我将函数的参数从int改为double,因为最后一行包含(n/c),如果c不是n的除数,整数除法会导致错误答案
你应该注意到f(n,c)=f(n-1,c)*(n/c)
因为n=n*(n-1)代码>提示:n/(c^n)
=(n-1)*n/((c^(n-1)*c)
。换句话说,f(n,c)==f(n-1,c)*n/c
。在代码中表达这一点留给读者作为练习。