I don’t know why the program returns int

Ok, so the main question is here.

double test = 1/3 * 3.14;

I understand what you need to do (1.0 / 3) to get the actual double number. But I wonder why. I would think that since you multiply by 3.14, this makes it double.

I understand correctly that whenever two values ​​are used in an arithmetic equation, no matter what happens around them, if they are integers, then you get an integer value?

T. x / y * z

while x is divided by y, is that all the program cares, and if they are both integers, will you get the integer value back? Only when you multiply it by z (3.14) does it become double.

+3
source share
4 answers

, . * / .

1 / 3 * 3.14 1 / 3. int, - , - int.

result * 3.14. - int, - double, . Java int double, . , - double.

+4

. / * -, , .

, 1/3, , 3.14 double s.

+3

Because according to the rules of arithmetic, 1/3 is calculated first. Since these are 2 integers, this is an integer division, resulting in 0. After that, you have a double calculation, but the error has already occurred.

+2
source

I understand that this is due to autoboxing in java. Java suggested that 1/3 separate the two ints so that you get int back (cast into a double).

If you made 1 / 3D, you will get 0.33333333 back

0
source

All Articles