+ 2
What to do to produce exact value while perform division in java?
3 ответов
+ 3
Thank you.I understood perfectly.
+ 2
float x = 5/2;
The reason why you get 2.0 is because both 5 and 2 are integer literals. So java does an integer division on them (result = 2) then it is assigned to a float variable, at this point the integer is implicitly converted to 2.0
If at least one of the operands on the right side is float, that will force java to do a float division instead. Float literals are suffixed with f or F and can have a decimal point, like 5.0f or 2.0F
You can make both operands float, or only one of them, in which case java will again implicitly cast the other integer number to float
float x = 5 / 2.0f;
float x = 5.0F / 2;
float x = 5.0f / 2.0f;
+ 1
Lalitha Leelavathi Kumari Make it 5.0f