1

I notice that I have two different result when I compile this operation in java, and python.

10 / 3 + 2 * 4 / 3 - 3

result in java = 2.0
in python = 3.0

I also execute this operation in many calculators and the result is 3.0 can anyone explain how java deal with this?

double var = 10/3+2*4/3-3;
System.out.println(var);
M A
  • 71,713
  • 13
  • 134
  • 174
user3417593
  • 33
  • 1
  • 7

3 Answers3

3

The expression components will be evaluated as integers, i.e. intermediate values are truncated (10/3 evaluates to 3, 2*4/3 evaluates to 2 and so on).

Changing to the below will result in 3.0:

double var = 10.0 / 3.0 + 2.0 * 4.0 / 3.0 - 3.0;
M A
  • 71,713
  • 13
  • 134
  • 174
2

In java :

10 / 3 + 2 * 4 / 3 - 3
(10 / 3) + (2 * (4 / 3))) - 3
3 + (2 * 1) - 3
3 + 2 - 3
2

Everything is cast to int, that why it's giving this result.

ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

Java follows a different order or operators than python:

Java : PMDRAS - parenthesis, multiplication, division , remainder, addition , subtraction.

Python : PEMDAS - Parenthesis, exponent , multiplication , division , addition , subtraction.

  • Since the operators that are different between the two languages are not present in the OP's question, how does this help? – NomadMaker Jun 13 '21 at 05:29