Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ Eulers number truncation

  1. Nov 6, 2013 #1
    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. jcsd
  3. Nov 6, 2013 #2

    UltrafastPED

    User Avatar
    Science Advisor
    Gold Member

    factorial is an integer function; cast it to float ...
     
  4. Nov 6, 2013 #3

    jedishrfu

    Staff: Mentor

    The 1/factorial will do integer division. You need to use 1.0 to get floating pt division.
     
  5. Nov 6, 2013 #4
    Thanks. Those must be the fastest responses I've ever had.
     
  6. Nov 7, 2013 #5

    Mark44

    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
  7. Nov 7, 2013 #6
    noticed that after posting.(the += thing the double I completely forgot about, thanks)
     
  8. Nov 7, 2013 #7

    rcgldr

    User Avatar
    Homework Helper

    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
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ Eulers number truncation
  1. Euler to Runge-Kutta 4 (Replies: 19)

  2. Euler's Method in Python (Replies: 13)

Loading...