Hello! This program is supposed to calculate an estimation of e to the power of x, but as soon as you enter the value of x, nothing happens. The program does not even end, I think it gets stuck in a while-loop, or it is just taking a really long time calculating the answer. What do you think and how do I fix it?
#include <iostream>
#include <cmath>
usingnamespace std;
int faculty(int z){
if(z<=0)
return 1;
elsereturn z * faculty(z-1);
}
double e(int y){
int k=1;
double sum = 0;
while(pow(y,k)/faculty(y)>pow(10,-7)){
sum += (pow(y,k)/faculty(y));
k++;
}
return sum;
}
int main(){
int x;
double answer;
cout << "-= e to the power of x estimation =-\nEnter x: "; cin >> x;
answer = e(x);
cout << answer;
return(0);
}
This expression pow(10,-7) can be written simply as the number 1e-7
The faculty (usually called factorial) function is called with the wrong variable.
The function double e(int y) is defined with an integer parameter. Normally ex is calculated where x is a floating-point value rather than an integer.
Something to think about: neither the factorial nor the pow functions are required in this program, as each term of the series may be derived from the previous by one multiply and one divide operation. Often it is a condition of completing this exercise that the cmath library is not to be used.
#include <iostream>
usingnamespace std;
double e(int y){
double sum=1;
int k = 1;
bool cp = true;
while(cp){
int sum1=1, sum2=1;
for(int z=0;z<k;z++)
sum1*=y;
for(int v=1;v<=k;k++)
sum2*=v;
if(sum1/sum2<10e-7)
cp=false;
else{
k++;
sum+=sum1/sum2;
}
}
return sum;
}
int main(){
int x;
double answer;
cout << "-= e to the power of x estimation =-\n\nEnter the value of x: "; cin >> x;
answer = e(x);
cout << answer;
}
A couple of comments. Well done for getting this to work without the use of <cmath>. The reason why this is useful to try is that the functions in that library are themselves written using techniques such as this, though highly optimised and tuned for the purpose.
A small point, you have used 10e-7 as the limit, that is 0.000001 while the original code had pow(10,-7) or 0.0000001. Notice these values are different. Perhaps you are not familiar with the use of scientific notation such as