Home Forums C Programming C program that computes the value of ex using a formula Re: Re: C program that computes the value of ex using a formula

#3501
GWILouisaxwzkla
Participant

try:


/****************************************************************
* File Name : c:programstempCG.cpp
* Date : December,15,2008
* Comments : new project
* Compiler/Assembler :
* Modifications :
*
*
*
*
*
* Program Shell Generated At: 3:08:27 p.m.
=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


#include < iostream >
//#include < string.h >
//#include < conio.h >
#include < math.h >
//#include < iomanip >
//#include < ctype.h >

using namespace std;

//main function ******************************

int main ( )
{

int terms;
double powerOfX;
double e = 1;
double i = 1;
double j ;
double k = 2;

printf ( "Enter value of x : " );
scanf ( "%lf" , & powerOfX );
printf ( "Enter the number of terms ( greater or equal to one ) : " );
scanf ( "%i" , & terms );
j = powerOfX;



while ( terms > 1 )
{
e = e + ( j * ( 1 / i ) );
terms --;
i = i * k;
j = j * powerOfX;
k ++;

}
printf ( "The approximated value of ex : %.12lf n" , e );
printf ( "The value of ex using C library function %.12lf: n" ,exp( powerOfX ) );
printf ( "The absolute difference between the two value : " );
printf ( "%.12lf n" , fabs ( exp ( powerOfX ) - e ) );
return 0 ;
}

I didn’t know how many digit to output so I chose 12 like the example. You can change this by changing the number listed after the ‘.’ in the last printf() statements.

Theres an error in the code I posted for the approximation of e = 1 + 1/1! + 1/2! . Heres the proper code:



/****************************************************************
* File Name : c:programstempCG.cpp
* Date : December,15,2008
* Comments : new project
* Compiler/Assembler :
* Modifications :
*
*
*
*
*
* Program Shell Generated At: 3:08:27 p.m.
=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


#include < iostream >
//#include < string.h >
//#include < conio.h >
#include < math.h >
//#include < iomanip >
//#include < ctype.h >

using namespace std;

//main function ******************************

int main ( )
{

int terms;
double powerOfX;
double e = 1;
double i = 1;
double j ;
double k = 2;


printf ( "Enter the number of terms ( greater or equal to one ) : " );
scanf ( "%i" , & terms );

while ( terms > 1 )
{
e = e + ( 1 / i ) ;
terms --;
i = i * k;
k ++;

}
printf ( "The approximated value of e : %.12lf n" , e );
printf ( "The given mathematical constant e = 2.718281828459 n");
printf ( "The absolute difference between the two value : " );
printf ( "%.12lf n" , fabs ( 2.718281828459 - e ) );

return 0 ;
}