Need explanation

Can someone explain why


		float s = 20.0f * 65536.0f;
		System.out.println((int) (((9 - 1)) / s));

produces 0

But


		System.out.println((int) (((9 - 1)) / 20.0f * 65536.0f));

produces 26214

Order of operations.
PE MD AS
Parenthesis-Exponents --> Multiplication-Division --> Addition-Subtraction
Math operations are applied in this order of priority.

(9-1) / s is 6.1e-6
((9-1) / 20.0) * 65536 = 26214

In other words, add some parenthesis to your second statement to get the same behavior:

System.out.println((int) (((9 - 1)) / (20.0f * 65536.0f) ));

PEMDAS… right, but the 9-1 (Parentheses) just becomes 8, and then it turns into:


8 / 20.0f * 65536.0f

and the order shouldn’t matter with only multiplication and division right?

Division and multiplication are left-associative, meaning in this case that evaluation order of those expressions is left-to-right: [icode]((8 / 20.0f) * 65536.0f)[/icode]

You can see precedence and associativity info for Java’s operators here: http://cs.smu.ca/~porter/csc/465/notes/javapl_operators.html

Yes, it does.

Compare (1/2)3 to 1/(23).

Oh boy I had no idea I feel like an idiot!

This is the same with addition/subtraction, but this may be more intuitive.

Edit: I guess BurntPizza’s table shows this as well.

Yep. That still sometimes throws me off. I’m not very smart.

But (1-2)+3 is different than 1-(2+3)!

Actually, I hate that schools teach PEMDAS, because it confuses everyone until they run into this kind of situation. Then they have to unlearn it, and relearn the “left-associativity” of opposite operations.

It happened to me and many others. The worst part is, they just expect you to pick it up along the way.

I know the rules but I don’t trust myself. I just use lots of brackets, and even throw in a few line breaks and indents for the more complex expressions. Also local variables work like brackets and are self-documenting.


      float s = 20.0f * 65536.0f;
      System.out.println((int) (((9 - 1)) / s));

Can be rewritten as (using made up var names):


      float radius = 20.0f * 65536.0f;
      int strength = 9 - 1;
      int damage = (int) (strength / radius);
      System.out.println(damage);

IMO, this is the best way to structure expressions. They explain themselves, and going back through existing code to edit or revise these statements is much easier. Sad to say, much of my code is not like this, and now I’m paying the price :frowning:

If you learn PEMDAS properly, then you learn that Multiplication and Division have the same priority, so whichever comes first. Same with Addition and Subtraction.

Nothing is wrong with the technique, you probably just had a bad teacher.