简体   繁体   中英

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)

[ 在此处输入图片说明 ]

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!

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.

将强制转换添加到int:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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