It works if I enter 10 and then 2, it gives me 5. But I am applying it in another program and now let go to try and it does not give me the results that have decimals, that is, the division of 2/10
what 0.2
it would be 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's why you should do the
cast
any integer value to divide to one of typefloat
since thecast se realiza antes de la operación
The result of the operation between an integer and one of type
float
will be afloat
, before assigning the value to the variablediv
This code allows you to perform the division between decimals, since the variables are declared double which allows me to perform divisions and that the result gives me a decimal
You have two options:
Change your data types that you take from
Scanner
fromint
tofloat
, this because when you divide two integers the result will be another integer, leaving your variables like this:Cast your operation to the point you require, in this case floating point, so your variable
div
would look like this: