Search code examples
javainteger-division

Java integer division result as double?


I currently have this code:

    int kills = 1;
    int deaths = 2;

    double kdr = 0;

    if(kills > 0 && deaths == 0) {
        kdr = kills;
    } else if(kills > 0 && deaths > 0){
        kdr = kills/deaths;
    }

    System.out.println(kdr);

You can test it here.

Why is the output 0.00 and not 0.5?


Solution

  • If kills/deaths < 1, you get 0, since the output of integer division is integer. This 0 is then cast to 0.0 to fit the double variable in which you store it.

    In order to get a non-integer result, you have to cast one of the numbers to double :

     kdr = (double)kills/deaths;