Reputation: 512
I am trying to calculate a^(1/n)
, where ^
denotes exponentiation.
However, the following:
Math.pow(8, 1/3)
returns 1.0
instead of returning 2.0
.
Why is that?
Upvotes: 8
Views: 410
Reputation: 500873
The problem is that 1/3
uses integer (truncating) division, the result of which is zero. Change your code to
Math.pow(8, 1./3);
(The .
turns the 1.
into a floating-point literal.)
Upvotes: 17
Reputation: 16536
Try Math.pow(8, (1.0f / 3.0f))
instead.
1 / 3
will do an integer division, which will give you 8 ^ 0 = 1
Upvotes: 4
Reputation: 1912
1/3
becomes 0
(Because 1
and 3
are taken as int
literals).
So you should make those literals float/double...
Do:
Math.pow(8, 1f/3)
or
Math.pow(8, 1./3)
or
Math.pow(8, 1.0/3)
Upvotes: 5