How do math equations work in Java?

When I do something like this

int test = 5 + 3 * (4 - 1) / 2; 

I get 9. I suspected this was because the int was rounded down. However, when I do this,

 float test = 5 + 3 * (4 - 1) / 2; 

I also get 9. However, when I do this,

 float test1 = 5; float test2 = 4.5; float test = test1 + test2; 

The test finally displays 9.5. Can anyone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.

+6
source share
4 answers

In your second example, although you assign the result to a variable of type float , the calculation itself is performed exactly the same as in the first example. Java does not consider the type of destination variable to determine how to calculate the right side. In particular, the subexpression 3 * (4 - 1) / 2 leads to 4 .

To fix this, you can use floating point literals instead of integers:

 float test = 5 + 3 * (4 - 1) / 2.0f; 

Using 2.0f starts floating point calculations for an arithmetic expression.

+16
source

Although you present the result 5 + 3 * (4 - 1) / 2 in the float, the actual estimate is done with the precision of an integer, which means that division 9 / 2 returns 4, not 4.5, which you would get if they were rated as floats.

+3
source

Expressions have their own type. So start with:

 5 + 3 * (4 - 1) / 2 

Each value has its own type. This type has an int value, so it is the same as:

 ((int)5) + ((int)3) * (((int)4) - ((int)1)) / ((int)2) 

It is clear that we are dealing with ints. Only after it evaluates to 9 does it get a binding to the float.

+2
source

The short answer is that integer types work with modular arithmetic with module 1 and discard the remainder.

Since you drop test as an integer, modular arithmetic is used with module 1 (for example, 9.5 mod 1), int test = 5 + 3 * (4 - 1) / 2;

With a 32 or 64 bit float this will give 9.5; however, since you chose test as int , the remainder is discarded, and the value referenced by test is 9.

0
source

Source: https://habr.com/ru/post/923813/


All Articles