# C++ Eulers number truncation

1. Nov 6, 2013

### Superposed_Cat

Hi, just started c++ and I made this program to calculate the value of eulers number. It works in c# but truncates the decimal points as far as I can tell. What am I doing wrong?
Code (Text):

#include <iostream>

using namespace std;
int factorial(int a){
int b=1;
while(a>0){
b=b*a;
a--;

}
return(b);
}

int main()
{
float x=1.0;
for(int i=1;i<25;i++){
x=x+1/factorial(i);
}
cout <<x;

return 0;
}

2. Nov 6, 2013

### UltrafastPED

factorial is an integer function; cast it to float ...

3. Nov 6, 2013

### Staff: Mentor

The 1/factorial will do integer division. You need to use 1.0 to get floating pt division.

4. Nov 6, 2013

### Superposed_Cat

Thanks. Those must be the fastest responses I've ever had.

5. Nov 7, 2013

### Staff: Mentor

For more precision, use double instead of float.

Also, many programmers would write the assignment statement in the for loop as
Code (Text):
x += 1.0/factorial(i);
You can do something similar in the code in your factorial function.

Your indentation could be tweaked a bit to make your code more readable. On the plus side you used code tags - good!

Here's how I would indent this code. I have also added more spaces
Code (Text):
#include <iostream>

using namespace std;

int factorial(int a)
{
int b = 1;
while(a > 0){
b *= a;
a--;

}
return(b);
}

int main()
{
float x = 1.0;
for(int i = 1; i < 25; i++){
x += 1.0/factorial(i);
}
cout <<x;

return 0;
}

Last edited: Nov 7, 2013
6. Nov 7, 2013

### Superposed_Cat

noticed that after posting.(the += thing the double I completely forgot about, thanks)

7. Nov 7, 2013

### rcgldr

Note that 25! is greater than 2^83. 18! is greater than 2^52, so truncation will occur at i >= 18 when adding 1/i! to a double >= 2.0. You could reverse the order of the loop (for i = 20; i >= 1; i--) and use 64 bit integers for factorial (20! < 2^62), but it wouldn't make much difference.

Last edited: Nov 7, 2013