-1

I have written this piece of code in my computer and the result is 7 instead of 8 (the correct result ... I think).

I don't know why... Can somebody help me?

#include <stdio.h>

int main() {
  int num;
  num = (68/10.0 - 68/10)*10;
  printf("the result %d", num);
  return 0;
} 
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Mery
  • 11

1 Answers1

0

double typically represents exactly about 264 different numbers. 68/10.0 is not one of them,

As a binary64, 68/10.0 is about 6.7999999999999998223643161..., the closest value to 6.8 that is a multiple of a dyadic rational. @ AntonH

68/10 is an integer division with a quotient of 6.

(68/10.0 - 68/10)*10 is thus about 7.9999999999999982236431606...

Assigning that to an int is 7 not 8 as the fraction is discarded even though it is very close to 8.

When converting a floating point value consider round to the the closest, rather than truncating.

num = lround((68/10.0 - 68/10)*10);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256