Hello,
I have been trying to figure out what I'm doing wrong on my program for two days. My professor keeps "forgetting " about me. It is due tomorrow. We are supposed to use the "summing estimator" to calculate an estimated value for exp(x) using the formula 1+ x^n/n! for a user entered value for x, and values for n from 1 to 100. I know my problem is in the logic of how to implement the formula in C++ because it compiles but gives the wrong values. I can't figure it out. Please help. Here is my program so far:
//
//
// This program will take an entered value 'x'
// and run an estimated calculation for e^x and
// also a calculation based on existing c++ exponent
// functions.
//
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double x; // Value entered by the user
double factorial(doubl e n);
double sum (double factors);
int main()
{
double estimate;
cout << setiosflags(ios ::fixed) << setprecision(5) ;
cout << "Enter a value for 'x' =>";
cin >> x;
estimate = 1 + sum(x);
cout << "The estimated value for pi is " << estimate << ".\n";
return 0;
}
// Function calculates n!
double factorial (double n)
{
double ans;
if (n<=1)
ans = 1;
else
ans = n * factorial(n-1);
return ans;
}
double sum (double factors)
{
double sum;
for (double n=1; n<=100; n++)
sum = pow(x,n)/factorial(x);
return sum;
}
I have been trying to figure out what I'm doing wrong on my program for two days. My professor keeps "forgetting " about me. It is due tomorrow. We are supposed to use the "summing estimator" to calculate an estimated value for exp(x) using the formula 1+ x^n/n! for a user entered value for x, and values for n from 1 to 100. I know my problem is in the logic of how to implement the formula in C++ because it compiles but gives the wrong values. I can't figure it out. Please help. Here is my program so far:
//
//
// This program will take an entered value 'x'
// and run an estimated calculation for e^x and
// also a calculation based on existing c++ exponent
// functions.
//
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double x; // Value entered by the user
double factorial(doubl e n);
double sum (double factors);
int main()
{
double estimate;
cout << setiosflags(ios ::fixed) << setprecision(5) ;
cout << "Enter a value for 'x' =>";
cin >> x;
estimate = 1 + sum(x);
cout << "The estimated value for pi is " << estimate << ".\n";
return 0;
}
// Function calculates n!
double factorial (double n)
{
double ans;
if (n<=1)
ans = 1;
else
ans = n * factorial(n-1);
return ans;
}
double sum (double factors)
{
double sum;
for (double n=1; n<=100; n++)
sum = pow(x,n)/factorial(x);
return sum;
}
Comment