Вычисление математической константы e с использованием цикла while - PullRequest
0 голосов
/ 01 июля 2011

В настоящее время я выполняю задачу в книге, которая просит меня вычислить математическую константу e, используя цикл while. Я справился с этим довольно легко, однако у меня проблемы с вычислением 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;
}

Есть идеи, где расчеты пошли не так?

1 Ответ

3 голосов
/ 01 июля 2011

Эта строка:

exponent *= exponent;

неверно.Должно быть:

exponent *= temp;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...