我知道有很多有关此问题的示例,但我尝试自己编写一个不同的示例。
这是使用泰勒级数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
关于c++ - C++程序计算e ^ x,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32793675/