0

I'm trying to divide an integer by a float using this simple code:

float result = 0;
int randomInt = [random integer between 100 and 500];
result = 323 / 10.00;

printf("result is: %f\n",result);

The output of printf is sometimes off by 0.00001 or so:

32.999998  //323/10.00
45.000001  //450/10.00
29.099998  //290/10.00

Why does this happen?

paddy
  • 60,864
  • 6
  • 61
  • 103
Noideas
  • 31
  • 3
  • Since the `float` representation used by most implementations is good for only 6-7 decimal digits of precision, you should consider using a `printf` format that avoids emitting more. For your particular case, maybe `%.4f` to get results rounded to four digits after the decimal point (as your particular outputs will always have exactly two digits before the decimal point, for six digits total). – John Bollinger May 30 '23 at 03:23
  • Aside: "divide an integer by a float" --> `323 / 10.00` is an `int` divided by a `double`. – chux - Reinstate Monica May 30 '23 at 03:26
  • "Why does this happen?" --> `float` can represent about2^32 different values. 3.23 is _not_ one of them. A value near `32.999998` is the closet `float.` – chux - Reinstate Monica May 30 '23 at 03:27
  • Consider `7/3` also forms an "off-precision result" of 2 and not 2.333333.... Some operations with a computer differ than _math_. – chux - Reinstate Monica May 30 '23 at 03:46
  • 1
    Hi also dividing integers in C and assigning the result to a double is the perfect example of why you need to cast your integer to float first before trying the operation – Son of Man May 30 '23 at 08:02
  • @Yunnosch, yeah I agree. – Son of Man May 30 '23 at 08:22
  • I doubt the example outputs are valid (at least not matching the comment behind). `450/10.0` and `290/10.0` have exact results and `323/10.0` should be something like `32.299...` or `32.30...1` – chtz May 30 '23 at 09:21

0 Answers0