有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取错误:可能存在从double到int的有损转换。。。。但我没有用替身?

我已经做了很多研究,我相信这只是一些愚蠢的事情,所以我提前道歉。我正在尝试CodinGame挑战,我正在使用这批代码

class Player {

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);

    // game loop
    while (true) {
        int x = in.nextInt();
        int y = in.nextInt();
        int nextCheckpointX = in.nextInt(); // x position of the next check point
        int nextCheckpointY = in.nextInt(); // y position of the next check point
        int nextCheckpointDist = in.nextInt(); // distance to the next checkpoint
        int nextCheckpointAngle = in.nextInt(); // angle between your pod orientation and the direction of the next checkpoint
        int opponentX = in.nextInt();
        int opponentY = in.nextInt();
        int distX = Math.abs(x - nextCheckpointX);
        int distY = Math.abs(y - nextCheckpointY);
        int distance = Math.sqrt(distX * distX + distY * distY);

这一点更进一步,但最后一行是我的问题所在。我已经注释掉了代码的其余部分,以确保这是发生错误的地方

现在,我知道如果我取一个int的平方根,我可能得到一个double,但是如果我把变量设置为int,那么它应该只存储为int。。。正当我甚至尝试将其存储为double或float(我无论如何都不希望这样),但它仍然会给我这个错误。我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    Math.sqrt()返回一个double,因此需要显式地将结果强制转换为(int),以告诉编译器您知道可能有信息丢失。毕竟,如果结果是2.125,那么在int变量中会出现2。编译器只是确保您理解这一点,而不是默默地删除小数部分

    因此,添加显式强制转换

    int distance = (int) Math.sqrt(distX * distX + distY * distY);
    

    请记住,将6.99转换为int并不会将^{转换为7,而是将^{转换为6,这可能不是你想要的。请参见Math.round()了解值的舍入