3

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

我已经完成了所有事情,直到 for 循环。我不太明白在新的和以前的数字大致相同之后我应该如何停止 for-loop。

这是我的功能:

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

这是我在 main 方法中的 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
4

3 回答 3

5

首先,如果 i 从 0 开始,然后你继续乘以 2,它不会前进很远。从 1 开始。

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

于 2011-03-24T00:16:56.813 回答
2

不要忘记有多个循环结构可用;对于此特定do ... while ()算法,循环可能是更好的选择。(是的,我相信你可以让它适合一个for循环,但它可能读起来不太清楚。)

于 2011-03-24T00:17:22.063 回答
1

它没有说使用 for 循环。你可以,虽然我认为一段时间或 do-while 更具可读性。无论哪种方式,您都需要一个条件,例如:

while(abs(prevValue - value) >= threshold)

编辑:固定。严格来说,应该是>=

编辑 2:您可以从人工prevValueand开始value,例如 0 和 1,或使用 do-while(如前所述)。

do
{
  // ...
} while(abs(prevValue - value) >= threshold);
于 2011-03-24T00:15:39.160 回答