9

I've been thoroughly searching for a proper explanation of why this is happening, but still don't really understand, so I apologize if this is a repost.

#include <iostream>
int main()
{
    double x = 4.10;
    double j = x * 100;

    int k = (int) j;

    std::cout << k;
 }

 Output: 409

I can't seem to replicate this behavior with any other number. That is, replace 4.10 with any other number in that form and the output is correct.

There must be some sort of low level conversion stuff I'm not understanding.

Thanks!

Koma
  • 93
  • 1
  • 3
  • possible duplicate of [strange double to int conversion behavior in c++](http://stackoverflow.com/questions/1860783/strange-double-to-int-conversion-behavior-in-c) – Oliver Charlesworth May 02 '11 at 01:49
  • 1
    It just makes my head spin trying to wrap it around someone reporting a problem like this without offering information about what problem they are having. – Jonathan Wood May 02 '11 at 02:03

3 Answers3

17

4.1 cannot be exactly represented by a double, it gets approximated by something ever so slightly smaller:

double x = 4.10;
printf("%.16f\n", x);  // Displays 4.0999999999999996

So j will be something ever so slightly smaller than 410 (i.e. 409.99...). Casting to int discards the fractional part, so you get 409.

(If you want another number that exhibits similar behaviour, you could try 8.2, or 16.4, or 32.8... see the pattern?)

Obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

The fix

int k = (int)(j+(j<0?-0.5:0.5));

The logic

You're experiencing a problem with number bases.

Although on-screen, 4.10 is a decimal, after compilation, it gets expressed as a binary floating point number, and .10 doesn't convert exactly into binary, and you end up with 4.099999....

Casting 409.999... to int just drops the digits. If you add 0.5 before casting to int, it effectively rounds to the nearest number, or 410 (409.49 would go to 409.99, cast to 409)

Phil Lello
  • 8,377
  • 2
  • 25
  • 34
1

Try this.

#include <iostream>
#include "math.h"
int main()
{
double x = 4.10;
double j = x * 100;

int k = (int) j;

std::cout << trunc(k);
std::cout << round(k);
}
mattnz
  • 517
  • 2
  • 13