Java integer division result as double?

2.3k views Asked by At

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?

2

There are 2 answers

2
Eran On BEST ANSWER

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;
0
Jens On

Because your input values are integer. if you cast one oy them to a double youget the expected result:

 kdr = (double)kills/deaths;