开发者

Calculating mathematical constant e using while loop

I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:

#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;
}

However, when I tried e^x the following code returned a completely wrong value:

#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;
      开发者_C百科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;
}

Any ideas where the calculations went wrong?


This line:

exponent *= exponent;

is wrong. It should be:

exponent *= temp;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜