将double转换为int(java)

时间:2016-01-03 13:57:12

标签: java int double type-conversion

我试图制作一个模拟太阳系的程序。

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);

为了让我的行星绕太阳转,我有一个公式;问题是我有这个公式的双数,我不能让他成为一个int(我试过地板(X),Math.round(X),没有工作(错误:不兼容)类型:可能从long转换为int的有损转换

[enter image description here]

你会发现它不是真正的java,但他是Java(它是一些Javascool),所以你的建议可能对我有用!

2 个答案:

答案 0 :(得分:2)

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.

答案 1 :(得分:0)

将强制转换添加到int,如:

posX = (int) Math.round(X);
相关问题