# a = 0.7f but at 0.7

1

Why a floating type variable with a value of 0.7 ... when subjecting it to the following condition: (if a < 0.7) ... expecting that if it is less, the word "yes" will be printed and if it is not, print the word "no"? The image exceeds 2mb. But the result of running the program is "Yes."

Code (java)

``````public comp ()
{
float a = 0.7f;

if (a < 0.7)
System.out.println("Si");
else
System.out.println("No");
}
``````

asked by Jostem97 30.11.2017 в 00:49
source

2

Java uses the doubles numbers by default to indicate real values, that is:

• the 0.7 that you use in the comparison is double.

• variable `a` declared is floating.

Floating and doubles numbers are implemented using the IEEE 754 standard, and have differences:

• float: 1bit for the sign, 8 bits for the exponent, and 23 for the mantissa = 32 bits.

• double: use 1 bit for the sign, 11 bits for the exponent, and 52 bits for mantissa = 64 bits.

So both make mistakes, but the error of the float 0.7 is greater than that of the double 0.7.

Using the following tool we can see:

float 0.7:

``````signo   exponente    mantisa
0     01111110     1 .01100110011001100110011
valor real: 6.9999999e-1
``````

double 0.7

``````signo  exponente    mantisa
0      01111111110  1 .0110011001100110011001100110011001100110011001100110
valor real: 7.0000000000000000e-1
``````

The actual values are different as seen. the double value is greater than the float value for that reason the yes is printed.

References: