-7
float   num = 0.5;
double num2 = 0.5;
if( num == num2)
   printf("Equal");
else
   printf("Not Equal");

How is it possible?

  1. The binary value of float 0.5 is 00111111 00000000 00000000 00000000
  2. The binary value of double 0.5 is 00111111 11100000 00000000 00000000 00000000 00000000 00000000 00000000

Please explain step by step because I'm new to programming

Muniyasamy V
  • 81
  • 1
  • 4
  • 9

2 Answers2

1

Inside the comparison, the float value is implicitly converted to type double.

Then the two values of the same type are compared.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • according to your perspective float 0.1 implicitly converted to double and result will be equal(true) ...But actual result is Not Equal(false).. – Muniyasamy V Mar 02 '17 at 13:46
  • @munyasamyv: In the statement `float x = 0.1;`, the `double` value of `0.1` is converted to `float` type losing precision. Later, when comparing the value with loss of precision (after conversion to `double`) with another (`double`) `0.1` they are different. In other words `(double)(float)0.1 != 0.1` – pmg Mar 02 '17 at 18:17
0

You should look up IEEE764 float and double definitions to see how real numbers are really stored, and what the binary-point offsets are for floats and doubles. The endian-ness of the machine will also affect things.

FredK
  • 4,094
  • 1
  • 9
  • 11