将double转换为int(java)
我正试图制作一个程序来模拟太阳系将double转换为int(java),java,int,double,type-conversion,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); for(int i
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);
for(int i=0;i向int添加cast,如:
posX = (int) Math.round(X);
当您将double
转换为int
时,编译器无法确定这是否是一个安全操作
double d = ...
int i = (int) d; // implicitly does a floor(d);
在Java8中,有一个函数可以帮助检测强制转换是否安全(至少从很长的时间内)
您可以将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.
请将您的代码复制并粘贴到您的问题中,而不是imagefor(int i=0;它在这里,但我不知道另一个如何在该网站中有一些“干净”的代码行:/请使用链接更新您的问题。注释不是用于代码。您可以使用{}
按钮格式化。非常感谢!)非常感谢!:)@M.Rio,因为您是新来的。所以,让你知道,你可以通过投票和接受他们的答案来感谢人们的帮助。
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.