2013-02-27 163 views
4

我想在java中運行此代碼並獲得以下錯誤,要求int發現雙精度。可能會丟失精度

public class UseMath{ 
public static void main(String[]args){ 
    int x = Math.pow (2,4); 
System.out.println ("2 to the power of 4 is" + x); 

} 
} 

請幫助....

+1

你在哪裏得到的錯誤?你確定這不是相反的方式嗎? [Oracle說](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html)'Math.pow()'需要雙打,你給它'ints' – MikeTheLiar 2013-02-27 21:21:41

+0

聲明'x'爲'double x = ...' – SRy 2013-02-27 21:25:45

回答

11

如果你看一看的documentation,它說,這Math.pow()需要兩個doubles,並返回一個double。當你將這個函數傳入int時,這意味着沒有傷害,因爲將int轉換爲double意味着沒有損失。但是,如果將值分配給int,則表示它可能會失去精度。

只要做到這一點:

int x = (int)Math.pow (2,4); 

double x = Math.pow (2,4); 
+0

謝謝我現在得到了輸出。 – Sandra 2013-02-27 21:34:59