+-
用C计算欧拉数
编写一个计算欧拉数e的程序.为此,首先编写一个带参数n的函数,然后返回结果(1 1 / n)n.当n接近无穷大时,该函数的极限接近e.在您的主程序中,编写一个循环,使用增加的n值调用此函数.在每次迭代中,将n乘以2(如果您每次只加1到n,算法就会“工作”),并在新近似值与之前的近似值相差小于1e-8时停止.现在你有一个很好的估计.所以在main()中,打印出最佳近似值和生成它的数字n.

我做了一切,直到for循环.我不太明白在新的和之前的数字大致相同之后我应该如何停止for循环.

这是我的功能:

double euler_finder(double n)
{
    return pow((1+1/n), n);
}

这是我在主方法中的for循环,其中???是我遇到问题的地方:

for (int i=0; i<????; i*=2) {

}

编辑:解决方案已发布,所以在这里看起来像:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double euler(int n);

int main()
{
    int trialN = 4;

    double guess1, guess2;

    guess1 = euler(1);
    guess2 = euler(2);

    while(  abs(guess1-guess2) > 1e-8 )
    {
        cout<< trialN << " " << guess2<<endl;
        guess1 = guess2;
        guess2 = euler( trialN );
        trialN*=2;
    }

    cout<<setprecision(8)<<"e is approximately "<<guess2<<" and we got it with a value of ";
    cout<<trialN<<" for n";

    return 0;
}

double euler(int n)
{
    return pow((1+1.0/n), n);
}

输出:

4 2.25
8 2.44141
16 2.56578
32 2.63793
64 2.67699
128 2.69734
256 2.70774
512 2.71299
1024 2.71563
2048 2.71696
4096 2.71762
8192 2.71795
16384 2.71812
32768 2.7182
65536 2.71824
131072 2.71826
262144 2.71827
524288 2.71828
1048576 2.71828
2097152 2.71828
4194304 2.71828
8388608 2.71828
16777216 2.71828
33554432 2.71828
67108864 2.71828
134217728 2.71828
e is approximately 2.7182818 and we got it with a value of 268435456 for n
最佳答案
首先,如果我从0开始,并且你继续乘以2,它将不会前进很远.从1开始.

其次,根据问题陈述,你应该在你的近似足够好时停止.所以循环停止条件不在i上,而是在abs(proper_E – your_approximation)> 1E-8

点击查看更多相关文章

转载注明原文:用C计算欧拉数 - 乐贴网