我目前正在做一本书中的任务,要求我使用 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/