Wrong answer by multiplying float and integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nitish19
    New Member
    • Jun 2015
    • 1

    Wrong answer by multiplying float and integer

    #include <stdio.h>

    int main()
    {
    printf("Hello, %d \n",(int)(64.07 *100));

    return 0;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The answer is correct.

    64.07 * 100 is a double multiplied by an integer. Never a good idea to mix floating point with integers but in this case the 100 is converted to double and the result is double.

    Now you have (int)(64.07 * 100 ) which tells the compiler to treat the double as an int. Even though the bit layout of the double is not the bit layout of an int. That cast does not convert the double to an int. All it does is tell the compiler to not be putting out warnings because you know more about what you are doing then the compiler does.

    You can't really convert a float to an integer since the integer has no decimal portion making any conversion inaccurate.

    Unless you have a really good reason for using floating point you should stick with integers.

    Comment

    • Zacariaz
      New Member
      • Jun 2015
      • 9

      #3
      I suppose the real is: "Why does 64.07 * 100 not simply equal 6407?"

      Well, can 64.07 be represented in binary? Let's try
      2^6 + 2^-4 + 2^-8...

      To be honest, there's really not point in trying, as the answer most definitely is no.

      Just like you can't represent 1/3, pi, sqrt(2), in decimal, you cannot represent 64.07 and many other numbers in binary.

      And since integer casts are always floored, that is to say rounded down, you result's one less that you'd expect.

      However you can get very very close, which is why if you remove the cast and change %d to %f, you will get the correct result.

      I suppose if you really want to do it your way you'd need to round it.

      Code:
      printf( "Hello, %d \n", lround( 64.07 * 100 ) )
      And voila! The correct result appears.

      And just to make sure there's not confusions, '%d' does not mean double, but signed integer. You need to use '%f' to print floats and doubles.

      Best regards.

      Comment

      Working...