[英]Convert double to 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);
為了使我的行星繞着太陽轉,我有一個公式: 問題是我在這個公式中有一個雙數,並且我不能讓他成為一個整數(我嘗試了floor(X),Math.round(X)無效(錯誤:不兼容的類型:可能有損從long到int的轉換)
[ ]
您會看到它不是真正的Java,但他是Java(它是Javascool),因此您的建議可能對我有用!
當您將double
轉換為int
,編譯器無法確定這是否是安全操作。 您必須使用諸如
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事件循環作為定期任務運行。
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.
將強制轉換添加到int:
posX = (int) Math.round(X);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.