Average =10/4; Returns 2.0 not 2.5 Pls suggest me to correct this | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Average =10/4; Returns 2.0 not 2.5 Pls suggest me to correct this

I'm a Java beginner

26th Apr 2020, 1:52 PM
Deepak Sandha
Deepak Sandha - avatar
1 Antwort
+ 1
In Java, an integer divided by an integer always returns an integer. So if 999 is divided by 1000, the answer instead of being 0.999, will be 0, because the decimal part is cut from the answer. In your case, 10 / 4 = 2.5. The decimal part 0.5 is cut out and the answer is 2. What you need to do is divide by a float or double 10.0 / 4 or 10 / 4.0 or 10.0 / 4.0 If it is a variable you can type cast it by doing float var = (float) variable_name / another_var;
26th Apr 2020, 2:04 PM
XXX
XXX - avatar