c++ - 使用 while 循环计算数学常数 e

标签 c++ while-loop

我目前正在做一本书中的任务,要求我使用 while 循环计算数学常数 e。我很容易地做到了这一点,但是我在计算 e^x 时遇到了麻烦,而用户输入了 x 和准确度。我用于计算 e 的代码是:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
      int conter = x;
      int intial = x;
      long double number = x;
      int counter = 1;
      while (conter > 1)
      {
             number = number*(intial-counter);
             counter++;
             conter--;
      }
      e += (1/number);
      x++;
}
cout << endl << "The mathematical constantr e is: " 
     << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}

但是,当我尝试使用 e^x 时,以下代码返回了一个完全错误的值:

#include <iostream>
#include <iomanip>
using namespace std; 

int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
      exponent = temp;
      int conter = x;
      int intial = x;
      long double number = x;
      int counter = 1;
      while (conter > 1)
      {
             number = number*(intial-counter);
             counter++;
             conter--;
      }
      int counterr = 1;
      while (counterr < x)
      {
            exponent *= exponent;
            counterr++;
      }
      e += (exponent/number);
      x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}

有什么地方计算出错了吗?

最佳答案

这一行:

exponent *= exponent;

错了。应该是:

exponent *= temp;

关于c++ - 使用 while 循环计算数学常数 e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6549532/

相关文章:

c++ - OpenCL:无效值

c++ - 压缩问题,zlib?

c++ - Binary 处理器如何区分两个相同字节大小的变量类型

python - python中的类变量重置

java - 带 readLine() 的 while 循环

c++ - 指针取不到数据

c++ - Qt初学者: QPainter widget not rendering

c++ - 为什么我的 do while 语句不起作用

linux - 使用 "while read"和 "for i in"导致不明确的重定向

javascript - 不知道为什么语法错误 ")"javascript