If i print the value of x for :
int a=1;
int b=6;
float x=(a/b);
The output is 0.0
But if i change the third line to float x = (float)a/(float)b;
The output is 0.1666667(which it should be)
Why the difference?
If i print the value of x for :
int a=1;
int b=6;
float x=(a/b);
The output is 0.0
But if i change the third line to float x = (float)a/(float)b;
The output is 0.1666667(which it should be)
Why the difference?
a/b
is calculated as the division of two integers and therefore its result is an integer, and so everything beyond the decimal floating point is truncated and you end up with 0.0
.
For example: if you had:
int a = 6;
int b = 4;
float x =(a/b);
You would get that x = 1.0
because the result of the calculation is truncated, and then when you assign it to a float, the integer result value 1
gets cast to a float, i.e. 1.0
.
When you calculate (float)a/(float)b
, you're calculating the division of two float
variables and the result is float
(the same would happen if only one of the variables / values was float
and the other one was integer
).
That is because both of the variables are of type int
and hence the division returns an int
.
You'll have to cast at least one of them to float
in order to force the division to return the result in float
.
Here is the code snippet:
public static void main (String[] args) throws Exception {
int a = 1;
int b = 6;
float x = ((float)a/b);
System.out.println("Result: " + x);
}
Output:
Result: 0.16666667
Note: In the above example, I have casted a
to float
. You can also cast b
to float
instead of a
as follows:
float x = (a/(float)b);