Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 9
#include <iostream>
#include <iomanip>
using namespace std;
//with this function we can calculate the factorial of a number n
float factorial(int n) {
if ((n==1)||(n==0)) {
return 1;
}
else {
return n * factorial(n-1);
}
}
//after this summation we should find the value of e
void numbere(int i, double& e) {
for (int j=0;j<=i;j++) {
e+=1.0/factorial(j);
}
}
//prints e
int main() {
double e=0;
numbere(10,e);
cout<<"The number e is equal to "<<e<<endl;
return 0;
}
+ 10
In main() you call numbere() without parameters;
try:
cout << "The number e is equal to "<< numbere(10) << endl;
+ 9
Another thing is you return before the loop ends in numbere(), so the value returned is wrong.
+ 9
Anyway you should use a reference to e (&) in numbere() since you want to modify it.
+ 9
The reason why it gives a wrong value is that you start the series at i=1 instead of 0. have fixed it now. See editing of previous code.
+ 8
@Frederico, yes I have noticed this. It does not work for long doubles apparently but works for floats or doubles.
+ 8
Your code gives me ~1.718 if I change e to a double type . Which is not correct. You will have to review your algorithm. ;)
+ 1
You are missing parenthesis
return ( e+= ( 1.0 / factorial (i) ) );
Assingment evaluates before any calculus