+ 2
How the calculation is done
In java while calculating any complex mathematical operation how do we proceed right to left or left to right? for example let initial values if a=2,b=5,c=5 then in the expression c=++a/b*c-a+++b; ++a evaluated first or ++b also plz give the final values of a,b,and c; any help will be highly appreciated
3 ответов
+ 2
There is something known as operator precedence. If you did maths, there is a concept called BDMAS , That is, First preference to brackets, next divide, next multiply, next add and finally subtract.
Modulo comes between Divide and multiply.
And for your second ques,a+++b shoulld be evaluated as a++ + b, start from left to right.
0
In most programming languages I've ever tried math is done the same as normally:
https://en.wikipedia.org/wiki/Order_of_operations
The important part here is the differences between ++var and var++. ++var is pre-increment style and will evaluate the value as value + 1 (effectively adding 1 to the value before evaluating it), whereas var++ is post-increment and will evaluate the value as it's current value, but then increase it after the evaluation (adding 1 to the variable after evaluating it).
So, in the expression above, if it's as it seems like it should be considering the lexer/parser should start at the left and move to the right when reading the line:
c= ( ++a / b * c ) - a++ + b; // where a = 2, b = 5, c = 5
c = (( ++2 / 5 ) * 5 ) - 2++ + 5 =
(( 3 / 5 ) * 5 ) - 2 + 5 =
(( 0.6 ) * 5 ) - 2 + 5 =
( 0.6 * 5 ) - 2 + 5 =
3 - 2 + 5 =
1 + 5 = 6
And A, B, and C would be: a = 4, b = 5, c = 6
And if it actually is c=( ++a / b * c ) - a + ++b then:
c = (( ++2 / 5 ) * 5 ) - 2 + ++5 =
(( 3 / 5 ) * 5 ) - 2 + 6 =
(( 0.6 ) * 5 ) - 2 + 6 =
( 0.6 * 5 ) - 2 + 6 =
3 - 2 + 6 =
1 + 6 = 7
And A, B, and C would be: a = 3, b = 6, c = 7
I've been up for around 48 hours though, so *please* feel free to point out any errors here.
Edit: forgot to include final values of A, B, C.
0
only 1 more doubt how to decide that in the expression
........a+++b it is a++ +b or a + ++b