0
#include <stdio.h>

int main(void)  {
    double x = 5.1;
    x = x - 5;
    int y = x/0.1;
    printf("%d\n", y);
}

Why does y = 0 instead of the expected value of 1?

user438383
  • 5,716
  • 8
  • 28
  • 43
Maverick
  • 11
  • 2
  • 8
    The result of `x = x - 5;` may be *ever so slightly* less than `0.1`, which would cause the truncation of the result of `x/0.1` to be zero. – Adrian Mole Aug 23 '22 at 09:33
  • Try printing **the raw memory contents** of `x` after you subtract 5 from it, and of `double z = 0.1`. You will see that they're different. –  Aug 23 '22 at 09:35
  • it’s most likely due to rounding errors. when casting to an integer, floating point numbers get floored rather than rounded (called truncation). and just because 5.1-4 is a finite-decimal operation in base10, this isn’t necessarily the case for base2, which is what the cpu uses. therefore, the result could be something like 0.09999999992 or similar. – Psi Aug 23 '22 at 09:36
  • [5.1 - 5 is not 0.1](https://ideone.com/YmM2MD) – pmg Aug 23 '22 at 09:37
  • 1
    From testing in the javascript console subtracting `5.1 - 5` it actually comes out as `0.09999999999999964`. Which means that when dividing by 0.1 you actually get `0.9999999999999964` which means it is less than 1 and it is converted to 0 as an int. Floating points strike again. – Marko Borković Aug 23 '22 at 09:38
  • Aside from marked duplicated answer, you can can also take a look at nextafter() function: [How to find nearest next/previous double value](https://stackoverflow.com/questions/10160079/how-to-find-nearest-next-previous-double-value-numeric-limitsepsilon-for-give) `nextafter(5.1, 6.0)` will return nearest floating value after 5.1. In my system, this is 5.100000000000000533. In that way, `nextafter(nextafter(5.1, 6.0), 0.0)` will return actual closest number to 5.1, which is: 5.099999999999999645. So, with the code `double x = 5.1;` the actual value of x is 5.099999999999999645. – The Long Nguyen Aug 23 '22 at 10:06

0 Answers0