0

I was doing a java tutorial when I typed this in:

int a = 3;
int b = 4;
int c = 5;
int d = -a*b/c*a;
System.out.println(d);

The output was -6. However when I use a calculator, I get -36/5 based on the left to right precedence rule. Can someone please explain why there are different answers?

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
Gabriel
  • 1
  • 3
  • 6
    when you divide to `int`s, the result is an `int`. – Eran Oct 16 '17 at 08:44
  • 1
    Also note the precedence: `-3*4/5*3` -> `((-12/5)*3)` -> `-2 * 3` -> `-6`. – Maroun Oct 16 '17 at 08:45
  • Thanks @MarounMaroun . I understand now. I thought int extracted only the integer after the final answer and not during the calculation process. – Gabriel Oct 16 '17 at 08:51

1 Answers1

2

Try it again with doubles:

double a = 3;
double b = 4;
double c = 5;
double d = -a*b/c*a;
System.out.println(d);

The problem is that the division will convert the result to an int

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
  • I got -7.1999999999999999999999999999 which still isn't -6 when considering int taking only the integer. – Gabriel Oct 16 '17 at 08:49