0

I am new to java. I read here that when we're casting from an int to a double type, it happens automatically(as it's widening casting, not narrowing casting). However, when I tried it out by myself with the following code:

int a = 3;

int b = 11;

double sum = a/b;  //widening casting happens automatically

...but got the answer of 0.0 instead of 0.27. I know that this is wrong since a/b will return type int(0) and then that int will become a double of 0.0. However, I'm not sure how to fix this.

Thank you so much for help!

CodingChap
  • 719
  • 1
  • 5
  • 18

1 Answers1

2

Yes, an int value is automatically cast to a double value, but it's the result of the calculation a/b which is executed using the int rules (since both participants are int).

In other words, first 3 is divided by 11, which is 0, when done in the int world. Then that 0 is converted to the double value 0.0, which is then assigned to sum.

You can force the calculation itself to be done using double precision by casting either value to double, for example like this:

double sum = a / (double) b;
Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586