Java Error - What am I doing wrong with this exponential?
Alright so I've got t开发者_如何转开发his piece of code:
blah = (26^0)*(1);
System.out.println(blah);
Which produces the output 26, when it should be equal to 1. What am I doing wrong? What can I do to fix this?
I think you're confusing the ^
operator. In Java, the ^
operator does an exclusive-or operation. To get a power, you need to use Math.pow(a,b)
In Java, the operator ^
is not exponentiate, but rather bitwise-xor. Anything xor 0
is itself, so 26^0=26
, 26*1=26
Math.pow(base, exponent)
works. The ^
means Bitwise-XOR.
So, you should use:
blah = Math.pow(26, 0) * 1;
System.out.println(blah);
As the previous responses said you are actually doing a bitwise XOR (which results in 26) and then multiplying by 1. See Bitwise and Bit Shift Operators and Summary of Operators for more info. You should be using Math.pow(base, exponent) so Math.pow(26.0, 0.0) as described in the Math api
精彩评论