exponential and factorial

hi all,

i've been trying to sort my problem which is cannot figure it out what was the mistake. been trying to run the program and the debugger become slower. btw, i never face it before. yet, i need everyone helps to helping me with this problem.

i was told to write a program that computes the value of e to the power of x by using the formula

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

here what i've come out with. still trying to sort this problem. thanks everyone. have good day ! :)



#include<iostream>
#include<cmath>
#define e 2.718


using namespace std;

main()

{

//declare
int i,x,n;
double factorial,exp,num;

cout<<"enter value of x: ";
cin>>x;

for (x=0; x<=i; x++)

if (x == 0)
exp=1, factorial=1;
else
factorial=factorial*x, exp=1+(pow(e,x)/(factorial));


cout<<"e^x is: "<<exp;


}

Last edited on
i is uninitialized, also you first cin >> x and then immediately x = 0.
i initialize when x=0 the value of exp=1.

do i have to initialize i=1?
your loop must be like this:
1
2
3
4
5
6
for (i=0; i<=x; i++)

if (i == 0)
exp=1, factorial=1;
else
factorial=factorial*i, exp=1+(pow(x,i)/(factorial));

Also i think you never find factorial of another numbers, for example: 5 which is 5*4*3*2*1.. you must make function which will find factorial..
@RisteMK factorial=factorial*i makes sure that factorial is equal to the factorial of i.

for (i=0; i<=x; i++)

if (i == 0)
exp=1, factorial=1;
else
factorial=factorial*i, exp=1+(pow(e,i)/(factorial));

cout<<"e^x is: "<<exp;


let say i entered x=2,
output is 4.679376.

if we use calculator, e^2 = 7.389





Your algorithm is bad. Note that to calculate ex your code calculates ei. What you need is exp = exp + i'th term where i'th term is xi/i!.
Also, why would your for loop be from 0 to x ? x is the power and the number of loops is the number of terms you use. The two are unrelated (well, actually higher power may need more terms to give the same accuracy, but my point was that 2 might not be enough and that you may be having logic problems here).
Topic archived. No new replies allowed.