递归计算函数f = n!/(c^n)的值
Recursively calculating the value of the function f = n!/(c^n)
我在上周的测试中得到了这个问题:
/* 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更改为两倍,因为最后一行包含(n/c),而整数偏差会导致错误的答案,如果c不是n
的除数您应该注意到f(n,c) =f(n-1,c)*(n/c)
,因为n!=n*(n-1)!
相关文章:
- 指针没有更新它在void函数内部指向的值
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 使用基类指针调用基类的值构造函数的语法是什么?
- 数组初始值设定项的构造函数歧义
- 局部变量保留函数中的值
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 字符串函数返回奇怪的值
- 此递归函数的每次迭代的值存储在哪里?
- VkSurfaceKHR 指针的值在函数调用后更改,无需任何显式赋值
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 如何在函数外部访问函数中局部变量的值?
- 采用初始值设定项列表的构造函数
- 为什么我的虚函数不赋值?
- 为什么 ComPtr 的函数返回不同的值,然后 &?
- 双链表的擦除值函数,未知错误
- 类函数返回到另一个类函数返回打印不同的值
- 如何读取指针的值,因为这个指针是函数的返回?
- 专门C++使用指针值类型的通用迭代器的模板函数?