Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 递归计算函数f=n的值/(c^n)_C++_Recursion - Fatal编程技术网

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
。在代码中表达这一点留给读者作为练习。