Function problem

this program is supposed to work with functions outside the main function ok?
so ur asked for a program which will ask for aproximation number (n) and a value (x), and it will display the value of e^x with this formula

e^x = 1 + (x/1!) + (x^2 / 2!) + (x^3 / 3!) + ..... (x^n / n!)

got it?
its the value elevated to the n power divided by the factorial of n.

well so here its my program and it is working only if n <= 2 and i really dont know why :S i need to handle this in by friday before 11:59 pm so i'll apreciate any possible help



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

//this function obtains the factorial of any number, in this case n.
// by convention if n = 0 factorial = 1, that's why the if
double factorial (double x)
{
if (x != 0)
for ( double a = 2; a < x; a++)
x *= a;
else
x = 1;

return x;
}

// this function will obtain the result of a number elevated to a given power.
double potencia (double x, double n)
{
for (double a = 1; a < n; a++)
x *= x;

return x;
}
// this function was supposed to return the value of e^x, but as i said before,
// it only works if n < 2 :S
double vExp ( double x, double n)
{
double e = 0;
for (double a = 1; a < n; a++)
e += ( ( potencia(x, a) ) / ( factorial(a) ) );

e += 1;
return e;
}
// this is the program it asks for the values and displays the value of e^x
// using my function and the cmath function
int main()
{
double n,x, ex;

cout << "Define un grado de aproximacion:" << endl;
cin >> n;
cout << "Ingresa el valor de \'x\': " << endl;
cin >> x;

ex = vExp(x, n);

cout << ex << endl;
cout << exp(x) << endl;


return 0;
}


so there it goes if anyone discovers the failure please post it thanks
Please post your code inside [code][/code] blocks so it's easier to read and refer to certain lines.

Look at the for loop in your factorial function. You check a < x; to continue looping, but look at what happens to the value of x inside the loop....
Topic archived. No new replies allowed.