小编Mar*_*oon的帖子

我可以从迭代函数和递归函数中获得不同的结果吗?

我的代码应该计算序列的第 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)

c++ recursion sequence numerical-computing

-2
推荐指数
1
解决办法
58
查看次数

标签 统计

c++ ×1

numerical-computing ×1

recursion ×1

sequence ×1