Division in Java does not work well


It works if I enter 10 and then 2, it gives me 5. But I am applying it in another program and now it lets go to test and it does not give me the results that it has decimals, that is, the division of 2/10 that would be 0.2 does not show it to me.

Why? what am I doing wrong?

public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Introduce dos numeros para dividir\nNumero: ");
    int num1 = sc.nextInt();
    System.out.print("Numero: ");
    int num2 = sc.nextInt();
    float div = num1/num2;
    System.out.println("La division de "+num1+"/"+num2+" = " +div);


Lo que sucede que si divides dos números enteros el resultado será otro número entero.

That is why any integer value to be divided should be cast to one of type float since the cast se realiza antes de la operación

The result of the operation between an integer and a float will be a float , before assigning the value to the div variable

2/10 = 0.2  /* Pero como retorna un entero devuelve el 0*/
float div = (float)num1/num2; /* retorna 0.2*/
Scroll to Top