Java Math.pow not working

System.out.println(Math.pow(16, 0.5)); is 4.0

      

and

System.out.println(Math.pow(16, (1/2)));  is 1.0

      

Why??? I need to use a faction!

+3


source to share


1 answer


1/2 equals 0 due to integer division, so Math.pow(16, (1/2)

equals Math.pow(16, 0)

which equals 1.0.

To evaluate 1/2 using floating point division, you must specify either 1 or 2 to double:

System.out.println(Math.pow(16, ((double)1/2)));

      

Or use a double literal in the first place:



System.out.println(Math.pow(16, (1.0/2)));

      

or

System.out.println(Math.pow(16, (1/2.0)));

      

+11


source







All Articles