質問

I am new to JAVA, and I am trying to learn the language; please excuse me if I am being silly.

So I was testing out Math.Pow( ) and came across that when I use a division function in the second argument my result is always '1.0', no matter what the values I put in both the arguments. Help?

public static void main(String[] args) {

    double a= 27 , b = 1/3 ;
    System.out.println(Math.pow(a,b));
}

run: 1.0 BUILD SUCCESSFUL (total time: 0 seconds)

役に立ちましたか?

解決

1/3 is zero. Math.pow(a,0) is 1 for all a != 0, in particular for a = 27.

The 1/3 division is performed between two integers using integer division, before the result is converted to a double. You can get the result you are looking for by ensuring that the number is done using double division, e.g. 1.0/3.

他のヒント

1/3 is integer division, which would evaluate to 0 as an integer first before setting it equal to b. That would make b = 0, so Math.pow(27, 0) = 1.

Change that to 1.0/3.0, then it becomes 0.3333. This is what you want.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top