简体   繁体   English

将double转换为int(java)

[英]Convert double to int (java)

I'm trying to make a program to simulate the solar system. 我正在尝试制作一个程序来模拟太阳系。

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

To make my planets turning around the sun, I have a formula; 为了使我的行星绕着太阳转,我有一个公式: the problem is that i have a double number with this formula, and i can't make him become an int (i tried floor(X), Math.round(X), doesn't work (error : incompatible types : possible lossy conversion from long to int) 问题是我在这个公式中有一个双数,并且我不能让他成为一个整数(我尝试了floor(X),Math.round(X)无效(错误:不兼容的类型:可能有损从long到int的转换)

[ [ 在此处输入图片说明 ] ]

You'll see that it is not really java but he works as Java (it's some Javascool), so your advices will probably work for me! 您会看到它不是真正的Java,但他是Java(它是Javascool),因此您的建议可能对我有用!

When you convert a double to an int the compiler can't determine whether this is a safe operation or not. 当您将double转换为int ,编译器无法确定这是否是安全操作。 You have to use an explicit cast such as 您必须使用诸如

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

In Java 8 there is function to help detect whether the cast was safe (from a long at least) Math.toIntExact 在Java 8中,有一个函数可以帮助检测强制转换是否安全(至少很长时间) 。Math.toIntExact

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

You can do this running the GUI Event Loop as a periodic task. 您可以将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM