[英]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.