Entering: (10+(2*3))*(2^(1+2))
into the interaction window gives the faulty result of '16'
when it should be 128. This is quite likely due to the
statement being incorrectly parsed in terms of
parenthesis.
I ran across an identical error writing a calculator
program. In parsing the statement in broke the
statement down recursively and was then attempting to
evaluate (1+2)). This evaluated to 0 instead of three,
causing the entire statement to evaluate incorrectly to
16.
I fixed this in my own program by carefully rewriting the
loop that counted parenthesis as so:
This loop ensured that inner items were processed first.
In doing so it kept a count of how many parenthesis it
had passed, +1 for a left paren, and -1 for a right
paren. Having the imbalance in the expression, that is
one left paren and two right paren's messed up the
count, and the inner expression 1+2 was never
evaluated, but returned '0'.
This bug is visible in the interactions pane, as well as a
System.out.println command in an actual java class.
-jack
JHebert@gmail.com
Logged In: YES
user_id=952966
In C, C++, and Java, the ^ operator is not an "exponent"
operator like in some other languages. Rather, this
operator is a "bitwise exclusive OR."
For example:
3[decimal] = 0011[binary]
2[decimal] = 0010[binary]
then (3 ^ 2)[decimal] = (0011^0010)[binar] = 0001[binary] =
1[decimal], since the right-most bit is the only bit in
which the two operands differ.
To evaluate the exponent in Java you must use the Math
library. E.g. Math.pow(2,3) = 8.0.