0

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?

Eran
  • 387,369
  • 54
  • 702
  • 768
ThatGuy343
  • 2,354
  • 3
  • 30
  • 55
  • This is a duplicate of many things. Just because you're assigning the result of an operation to a `double` doesn't make the operation itself get performed using `double` arithmetic... – Jon Skeet Nov 12 '14 at 07:26

2 Answers2

3

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;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you. I should've tried that, i just assumed that dividing under a double would not need a cast. – ThatGuy343 Nov 12 '14 at 07:28
  • 1
    @ThatGuy343 Your division is performed on two integers, and therefore results in integer, and only the result is cast to double, to fit your kdr variable. – Eran Nov 12 '14 at 07:31
1

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

 kdr = (double)kills/deaths;
Jens
  • 67,715
  • 15
  • 98
  • 113