Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }
3rd May 2017, 1:04 PM
Karl T.
Karl T. - avatar
+ 10
In main() you call numbere() without parameters; try: cout << "The number e is equal to "<< numbere(10) << endl;
3rd May 2017, 12:49 PM
Karl T.
Karl T. - avatar
+ 9
Another thing is you return before the loop ends in numbere(), so the value returned is wrong.
3rd May 2017, 12:52 PM
Karl T.
Karl T. - avatar
+ 9
Anyway you should use a reference to e (&) in numbere() since you want to modify it.
3rd May 2017, 1:00 PM
Karl T.
Karl T. - avatar
+ 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.
3rd May 2017, 2:54 PM
Karl T.
Karl T. - avatar
+ 8
@Frederico, yes I have noticed this. It does not work for long doubles apparently but works for floats or doubles.
3rd May 2017, 2:41 PM
Karl T.
Karl T. - avatar
+ 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. ;)
3rd May 2017, 2:46 PM
Karl T.
Karl T. - avatar
+ 1
You are missing parenthesis return ( e+= ( 1.0 / factorial (i) ) ); Assingment evaluates before any calculus
3rd May 2017, 12:10 PM
⏩▶Clau◀⏪
⏩▶Clau◀⏪ - avatar