gpt4 book ai didi

计算e^x的C++程序

转载 作者:行者123 更新时间:2023-11-28 02:20:16 25 4
gpt4 key购买 nike

我知道这个问题有很多例子,但我试着自己写一个不同的例子。这是使用泰勒级数 e^x = 1 + x/1! + x^2/2! + x^3/3! + ......我的代码可以编译并运行,但它不会为某些推算输出正确答案,我不确定为什么。这是可用的代码还是我应该废弃它?

    #include <iostream>
#include <cmath>

using namespace std;
int main()
{
double final,power,end_n = 1.0,e=1.0,x=2.0, n;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1){
power = pow(x,n);
end_n = end_n*n;
e= (power/end_n)+e;
n--;
}
final =e+x;
cout<< final;
return 0;
}

最佳答案

老实说,我完全不知道您的推理是什么。该特定扩展的代码非常简单:

double x;
cin >> x;

double oldres, res=1, top=1, bottom=1;
int iter=1;

do {
oldres=res; // to calculate the difference between iterations

++iter; // next iteration
top*=x; // multiply by one x for each iteration
bottom*=(iter-1); // multiply by the iteration number for each iteration
res+=top/bottom; // and add the fraction to the result
} while(fabs(res-oldres)>.1); // while the difference is still large

cout << res; // done, show the result

关于计算e^x的C++程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com