2

What will be the answer for x for the following x = 27 * 24 \ 4 /2

is it 81 or 324 - considering that there is an integer division(/) which is said to have lower precedence than (/,*)

Your help in this regard will be much appreciated

  • what do you mean with ''? – A.P. Mar 25 '13 at 08:26
  • I would use parenthesis whenever I have such an expression, even if I know exactly which order is correct. To use parenthesis cannot be wrong, especially if you are asking for a programming language. This will help you or someone else read the expression later. – Djaian Mar 25 '13 at 08:59

1 Answers1

0

Interpreting '\' as division:

Usually multiplication and division have the same precedence, just like addition and subtraction, and are thought as left associative. Hence your operation gives $$ x = \left[(27*24)/4\right]/2 = 81 $$


If by '\' you mean "integer division", i.e. $a$ \ $b=\lfloor a/b\rfloor$, then probably it's precedence seems to depend on the programming language. In Python $(//)$ has the same precedence as $(*)$ and $(/)$. On the other hand in C++ $(/)$ is polymorphic (it's output depends on the type of the input values), while in Visual Basic it seems to have a lower precedence, indeed. In that case you would get $$ x= \left(27*24\right) \text{ \ } (4/2)=324 $$

A.P.
  • 9,728
  • Thank you very much, much appreciated! – user2206576 Mar 25 '13 at 09:35
  • The "integer division" operator certainly exists in C/C++, it is written 7 / 5. There is no "integer divided by integer gives real", you have to write for example (double) 7 / 5. Same precedence as *, associates to the left. Best bet, language independent: If you aren't 100% clear, use parentesis. Maybe you get it right, but it helps unconfuse whoever has to read your code later (probably youself in a week or so ;-). Parentesis are cheap; finding mysterious bugs due to misreading expressions is long drawn out, embarrasing, and expensive. – vonbrand Mar 25 '13 at 17:16
  • @vonbrand Sure, what I was trying to say is that there is no different operator('/' is polymorphic), so which division operator you use depends on the type of the numbers you are dividing, and you cannot mix the two divisions without an explicit cast. – A.P. Mar 25 '13 at 17:26
  • 1
    You can if your expression is int / int / double –  Mar 25 '13 at 17:35
  • @Hurkyl Didn't know that, thanks. – A.P. Mar 25 '13 at 17:36