计算e^x的C++程序

标签 c++ math

我知道这个问题有很多例子,但我试着自己写一个不同的例子。 这是使用泰勒级数 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/

相关文章:

c++ - 在 libtidy 中,如何读取字符串值选项

C++ operator< 重载结构

java - 获取 NaN 作为简单 Java 程序的答案

c++ - 完全数程序中的逻辑错误

javascript - 生成正态分布的随机值时,定义范围的最有效方法是什么?

c++ - 质量差,在 qt4 中渲染来自相机的图像时

c++ - 如何正确打印 __FILE__ 扩展到的字符串?

C++ -(零成本?)类似 operator=(value) 的代理 -> std::map[key]=value inside class

algorithm - 无放回和负权重的加权抽样

mongodb - 在搜索结果中查找 A & C