I am new to C++ as well. I examined your codes and came up with the following:
As guatemala007 suggested, I believe having the post decrement was probably not a good idea.
Several things I want to point out.
First, I changed int type to long long so those variable can store slightly larger integers.
Second, static_cast is not necessary on line 26 since it is dividing 1.0, which is double type, so the integer gets converted to double anyways during mixed operation.
Third, in the while loop in line 21, get rid of the post decrement and change >= to >. Then, you wouldn't need the while loop on line 24. Since 0! = 1, and any number multiplied by 1 is itself.
With those change, I got this and the result is positive, which is what you would expect
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
using namespace std;
int main()
{
// Changed type from int to long long to accommodate higher number (Factorials tend to get very large)
long long factorial, m, k, number;
double e = 0;
do{ cout << "Please enter a non-negative integer: ";
cin >> number; } while(number < 0);
k = number;
while( number >= 0 ){
m = number; // Create a working copy of number
factorial = 1; // Reset factorial to 1
// If number is 0, it will skip this while loop and factorial will be 1
while ( m > 0 )
{
factorial *= m;
m --;
}
// Debugging output to make sure Factorial has been calculated correctly. Comment out when finished
cerr << "Factorial is " << factorial << endl;
e += (1.0 / factorial);
number --;
}
cout << "The approximation of e with the sums of factorials " << k
<< "!" << " is " << e << endl;
return(0);
}
|
Test Run
1 2
|
Please enter a non-negative integer: 5
The approximation of e with the sums of factorials 5! is 2.71667
|