Division in Java does not work well

6

It works if I enter 10 and then 2, it gives me 5. But I am applying it in another program and now I release to try and it does not give me the results that it has decimals that is to say 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);
}
    
asked by TheKeviin 29.04.2017 в 18:07
source

3 answers

11

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 of any integer value to divide one of type float since the cast se realiza antes de la operación

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

2/10 = 0.2  /* Pero como retorna un entero devuelve el 0*/
float div = (float)num1/num2; /* retorna 0.2*/
    
answered by 29.04.2017 / 18:19
source
4

This code allows you to make the division between decimals, since the    variables declare double which allows me to make divisions and that the    Decimal me result

public static void main (String[] args) 
{
 Scanner sc = new Scanner(System.in);
System.out.print("Introduce dos numeros para dividir\nNumero: ");
double num1 = sc.nextDouble();
System.out.print("Numero: ");
double num2 = sc.nextDouble();
double div = num1/num2;
System.out.println("La division de "+num1+"/"+num2+" = " +div);
}
    
answered by 29.04.2017 в 18:23
3

You have two options:

  • Change your data types that you take from Scanner of int to float , this because when you divide two integers the result will be another whole number, leaving your variables like this:

    float num1 = sc.nextFloat();
    float num2 = sc.nextFloat();
    
  • Casting your operation to the point you require, in this case floating point, so that your variable div would look like this:

    float div = (float) (num1 / num2) ;
    
  • answered by 29.04.2017 в 18:19