division with whole numbers | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

division with whole numbers

public class FirstProgram { public static void main(String[] args) { double number = (1 / 3) * 3; System.out.println("(1/3) * 3 is equal to " + number); } } output: (1/3) * 3 is equal to 0.0 the final result should be 1.0, why its returns 0.0?

14th Feb 2017, 11:00 PM
Efraim Ié
Efraim Ié - avatar
3 Respuestas
+ 6
(1/3) is a integer division. Use (1/3.0) to make double division. Or explicit casting (1/(double)3).
15th Feb 2017, 3:19 AM
Salva Pérez
Salva Pérez - avatar
+ 5
It won't work with a fraction like 1/3. It equates this to 0. If you had two other variables for your numerator and denominator then it would work. Like this: public class FirstProgram { public static void main(String[] args) { double one, two, ifn; one = 1; three = 3; ifn = one/three; System.out.print(ifn); } }
14th Feb 2017, 11:07 PM
J.G.
J.G. - avatar
+ 3
This is because you're doing integer division first then multiplying and then implicitly converting that result to a double. 1/3 = 0 (With integer division the decimal part is truncated) 0 * 3 = 0 0 converted to double is 0.0
15th Feb 2017, 12:30 AM
ChaoticDawg
ChaoticDawg - avatar