Convert double to int (java)

怎甘沉沦 提交于 2019-12-12 03:32:28

问题


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)

[

]

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!


回答1:


Add cast to int like:

posX = (int) Math.round(X);



回答2:


When you convert a double to an int the compiler can't determine whether this is a safe operation or not. 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

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

You can do this running the GUI Event Loop as a periodic task.

 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.


来源:https://stackoverflow.com/questions/34577277/convert-double-to-int-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!