Write a program that computes the value of e-x by using the formula:
e-x= 1- x/1! + x2/2! - x3/3! + …
My code is this:
#include <iostream>
#include<cmath>
using namespace std;
void main()
{
double x;
cin>>x;
double sum=0;
int factorial=1;
for(int i=1;i<=30;i++)//I don't kno which number to chose because for high values when the compiler compiles i get values which say IDK..i thought 30 was the best choice..30! for instance is high enough)
{
factorial=factorial*i;
sum=(pow(-1.0,i)*(pow(x,i)/factorial) )+sum;
}
cout<<sum+1<<endl;//+1 is to account for the 1 in the sum
//I am not getting correct values please help me
}
Try using a double for the factorial calculation.
Or...Go a step further and calculate x^n as the loop proceeds, just as you are doing for factorial now.
ie:
1 2 3 4 5 6
double term = 1.0, sum = 1.0;
for( i=1; i<=30; ++i)
{
term *= -x/i; // no pow() function call needed!
sum += term;
}
EDIT: I see Vlads code is basically doing this same thing.