In: Computer Science
Build a program to calculate the value of e ( 2.71828) raised to the power of x (the independent variable). The function is based on the series expansion shown in class. Compare your result to the predefined function exp(x) as stated in the standard file ( cmath ). Your input will be " x" and "n" where n is the number of terms in the expansion and x is an arbitrary value of your choice. Have your output display your calculated value to the cmath value.
I am using C++, show in detail.
Screenshot of the code:
Sample Output:
Code To Copy:
//Include the header file.
#include <bits/stdc++.h>
using namespace std;
//Define the function to compute the
//e power x
float exp_func(int n, float x)
{
//Define the variable sum;
float result_sum = 1.0f;
for (int i = n - 1; i > 0; --i )
{
//Compute the sum of the exponential series.
result_sum = 1 + x * result_sum / i;
}
//Return the summation of the series.
return result_sum;
}
//Define the main function.
int main()
{
//Declare the variables.
int n;
float x;
//Prompt the user to enter the value of x.
cout << "Enter the value of x to raise the power: ";
cin >> x;
//Prompt the user to enter the number of terms.
cout << "Enter the number of n terms: ";
cin >> n;
//Display the resultant value of the series.
cout << "e^x = " << fixed << setprecision(5)
<< exp_func(n, x) << endl;
//Return the value for the main function.
return 0;
}