实现奈培数(e)与一个递归函数 [英] Implements neper number (e) with a recursion function
问题描述
我要计算内佩尔号(电子的)用递归函数。我有公式计算的:
I want to calculate Neper number(e) with a recursion function. I have the formula to calculate it:
E =(1/0!)+(1/1!)+(1/2!)+(1/3!)+。 。
e = (1/0!) + (1/1!) + (1/2!) + (1/3!) +. . .
我有code,但它不能正常工作:
I have the code but it won't work properly:
#include <iostream>
using namespace std;
double f(double res,int i, int n){
return (i == n) ? res: res = res + (1 /f(res,i+1,n)*i);
}
int main(){
cout << f(1,1,2) << endl;
}
这code的结果是 2.5
,但它应该是 2
。问题出在哪里?
The result of this code is 2.5
but it should be 2
. Where is the problem?
推荐答案
不过不知道你想要什么 RES
进行。事实上,如果我得到的符号创作 N
这并不需要我
或者
Still not sure what you want res
for. In fact, if I got creative with the sign of n
this doesn't need i
either.
double f(int i, int n)
{
return (i == 0) ? ((n <= 1) ? 1 : n * f(0,n-1))
: ((n < 1) ? 1 : 1/f(0, n) + f(i,n-1));
}
int main()
{
for (int n=1; n<16; ++n)
std::cout << std::setprecision(16) << f(1,n) << std::endl;
return 0;
}
输出
2
2.5
2.666666666666667
2.708333333333333
2.716666666666666
2.718055555555555
2.718253968253968
2.71827876984127
2.718281525573192
2.718281801146385
2.718281826198493
2.718281828286169
2.718281828446759
2.71828182845823
2.718281828458995
这是我的意思有关的标志玩弄于 N
来消除我还有:
This was what I meant about toying with the sign for n
to eliminate i as well:
double f(int n)
{
return (n < 0) ? ((n == -1) ? 1 : -n * f(n+1))
: ((n < 1) ? 1 : 1/f(-n) + f(n-1));
}
的结果是相同的。在两种情况下,函数被定义为两用它递归算法。当要求,它计算的1 / n!,否则它计算运算总和+下一个数字向下(即1 /(N-1)!,等...)
The results are the same. In both cases the function is defined to dual-purpose it recursive algorithm. When asked to, it computes 1/n!, otherwise it computes the running sum + the next number down (which is 1/(n-1)!, etc...)
这篇关于实现奈培数(e)与一个递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!