0

I think I understand why 0.1 + 0.2 == 0.3 returns 0: Because 0.1 + 0.2 output a double type, which 0.3 isn't...right?

Then why does 1 + 2 == 3.0 return 1 if the expression has different types?

#include <stdio.h>
int main()
{

  printf("0.1 + 0.2 == 0.3: %d\n", 0.1 + 0.2 == 0.3); // returns 0 (false).                                    
  printf("1 + 2 == 3.0: %d\n", 1 + 2 == 3.0);         // returns 1 (true) 
  
  return 0;
}
chickpea
  • 79
  • 8
  • 3
    Because it is not possible to represent tenths precisely with binary floating point arithmetic, but integers can be represented accurately (for a large range of values). – Jonathan Leffler Feb 22 '23 at 18:04
  • chickpea, "Because 0.1 + 0.2 output a double type, which 0.3 isn't...right?" --> No. `double` can encode exactly about 2^64 different values. 0.1, 0.2, and 0.3 are **not** in that set. What nearby values do you think the program uses? – chux - Reinstate Monica Feb 22 '23 at 21:43

0 Answers0