Forums Register Login

Confused in precedence and associativity rules

+Pie Number of slices to send: Send
Hi,

What is the value of evaluating the following expression (- -1-3 * 10 / 5-1)?

Select the one correct answer.
a)–8
b)–6
c) 7
d) 8
e) 10
f) None of the above.


Answer given is: b

Please i need more explanation on how this expression is evaluated according to precedence and associativity rules.

Thank you.
[ August 10, 2005: Message edited by: Adil El mouden ]
+Pie Number of slices to send: Send
That doesn't seem right. The answer should be b) -6
The best way to evaluate any mathematical expression is to try to bracket it properly

(- -1-3 * 10 / 5-1) = ((-(-1) - ((3 * 10) / 5)) - 1)

The expression on the rhs can now be evaluated by rules of arithmetic to give -6
+Pie Number of slices to send: Send
ooh! the answer given is : b sorry
I need more explanation.
Thank you.
[ August 10, 2005: Message edited by: Adil El mouden ]
+Pie Number of slices to send: Send
This code compiles as :
(-(-1)-((3*10)/5)-1)

= (1-30/5-1)
= 1-6-1
= -6

Which is the correct answer and not 7.
+Pie Number of slices to send: Send
I would like to point out, that multiplication and division has higher precedence than addition and substraction

(--1) gives 0

-(3*10/5) gives -5

-5 -1 gives result -6

;-)
+Pie Number of slices to send: Send
I would like to point out that

a) --1 is not a legal expression in java
b) - -1 gives 1
c) -(3*10/5) gives -6 in most cases
+Pie Number of slices to send: Send
The Result is simple BODMAS rule

B- Bracket
O - of
D- division
M - Multipilcation
A- addition
S- Subtraction

The Expression is (- -1-3 * 10 / 5-1)

it is divided as
- of -1 -3 * 10 /5 -1
that becomes

+1 -30/5 -1

that becomes

+1 -6-1
That becomes -6

Hope this puts some more light on the ongoing discussion,

Thanks
Tomorrow is the first day of the new metric calendar. Comfort me tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 883 times.
Similar Threads
++X
Array's Tricky Question
Logical operator precedence
++X
[K&B Java 5] both operands are fully evaluated before the operator is applied?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:33:06.