Problem with decimals

I'm a student and am taking a C++ class.  I am just learning so when another student came to me with question I didn't know how to answer it and neither did the teacher.  Basically the student tried to get the modulus with out using the mod funtion. Here's the code:

int w = 0;
int n = 23;
int d = 5;
double x = 0;

cout.setf(ios::scientific);
w = n/d;
x = n/
static_cast<double>(d)-w;
n=x*d;

when run 'n' comes out to be 2 not 3 like it should be.  Everything else worked 'w' is 4 and 'x' is .6.  I was just wondering why this would happen. If anyone could help that would be great.

                Thanks



Answer this question

Problem with decimals

  • moondancer10

    Do the following:

    x = ((double)n) / ((double)d) - ((double)w);

    Greetings
      Jochen



  • A. L.

    Ok I see now thank you so much.  You were very helpful.
    James

  • maxaeran

    Take a look at the paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

    It is widely available at the Net. E.g. first search results points to http://docs.sun.com/source/806-3568/ncg_goldberg.html.

    In your particular case problem happens because 23/5 cannot be exactly represented as binary floating point number (see section "Floating-point Formats" in the abovementioned document).

    Thanks,
    Eugene

  • GAL

    Thank you for that information it was very interesting reading.  But it still leaves me confused since 23/5 is equal to 4.6 exactly. So I still don't see how there is an error in conversion to binary format. 

    Thanks,
      James

  • William Fields

    4.6 cannot be exactly represented in the binary format. Only fractions where denominator is power of 2 can. 4.6 == 4 + 3/5, i.e. denominator is 5.

    Thanks,
    Eugene

  • Problem with decimals