2016-01-03 236 views
0

我試圖製作一個程序來模擬太陽系。將double轉換爲int(java)

for(int i=0;i<1000;i++) { 
    double X=(160*Math.cos((2*PI*i)/365)); 
    double Y=(160*Math.sin((2*PI*i)/365)); 
    posX=Math.round(X); 
    posY=Math.round(Y); 
    cadre.repaint(); 
    sleep(200); 
} 
f.setVisible(false); 

爲了使我的行星圍繞着太陽轉,我有一個公式;問題是我有這個公式的雙數,我不能讓他成爲一個整數(我試圖(X),Math.round(X),不工作(錯誤:不兼容的類型:可能有損從長期轉換爲int)

[enter image description here]

你會看到,它不是真正的Java,但他的作品如Java(這是一些Javascool),所以你的建議可能會爲我工作!

+0

請圖像 –

+0

的複製並粘貼代碼到您的問題,而不是對(INT I = 0; I <1000;我++){ \t \t雙X =(160 * Math.cos((2 * PI * I)/ 365));雙Y =(160 * Math.sin((2 * PI * i)/ 365)); \t \t posX = Math.round(X); \t \t posY = Math.round(Y); \t \t cadre.repaint(); \t \t sleep(200); \t} \t f.setVisible(false); –

+0

這是在這裏,但我不知道其他如何在本網站有一些「乾淨」的代碼行:/ –

回答

0

添加投到int像:

posX = (int) Math.round(X); 
+1

非常感謝! :) –

+0

@ M.Rio因爲你是新來的。所以只是爲了讓你知道你可以通過提高投票和接受他們的答案來欣賞人們的幫助。 – Harinder

1

當您轉換爲doubleint編譯器無法確定這是否安全操作。你必須使用顯式類型轉換,如

double d = ... 
int i = (int) d; // implicitly does a floor(d); 

在Java 8有功能,以幫助檢測中投是否是安全的(從長至少)Math.toIntExact

int i = Math.toIntExact((long) d); // implicitly does a floor(d); 

爲此,您可以運行GUI Event Loop作爲週期性任務。

double X= 160*Math.cos(i * 2 * PI/360); 
double Y= 160*Math.sin(i * 2 * PI/360); 
posX = Math.toIntExact(Math.round(X)); 
posY = Math.toIntExact(Math.round(Y)); 
cadre.repaint(); 
// note you have to return so the image can actually be drawn. 
+0

非常感謝! :) –