我的代码应该计算序列的第 100 个元素$x_0=1 ; x_i=\dfrac{x_{i-1}+1}{x_{i-1}+2}, i=1,2, \ldots$
我写了迭代和递归函数,但结果不相等。是因为丢失了小数吗?
这是我的驱动程序代码。文件中的数据是 i=100。
int main()
{
int i;
ifstream f ("data.txt");
f >> i;
double x_0= 1.00;
double x_100 = l(x_0, i);
ofstream g ("results.txt", ios::app);
g <<"\n100th element (by looping): " << x_100;
x_100 = r(x_0);
g <<"\n100th element (by recursion): " << x_100;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
l()是迭代函数,
r()是递归函数
double l(double x, int i)
{
for (int j = 0; j<i ; j++){
x = (x + 1)/(x+2);
} …Run Code Online (Sandbox Code Playgroud)