What is causing my C++ program to truncate Euler's number?

  • Context: C/C++ 
  • Thread starter Thread starter Superposed_Cat
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 3K views
Superposed_Cat
Messages
388
Reaction score
5
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:
#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;
}
 
Physics news on Phys.org
Thanks. Those must be the fastest responses I've ever had.
 
For more precision, use double instead of float.

Also, many programmers would write the assignment statement in the for loop as
Code:
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:
#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:
  • Like
Likes   Reactions: 1 person
noticed that after posting.(the += thing the double I completely forgot about, thanks)
 
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: