简体   繁体   English

从double到int的可能有损转换?

[英]Possible lossy conversion from double to int?

This is the message I get when I try to compile my code. 这是我尝试编译代码时收到的消息。 What exactly does it mean and how can I fix this? 究竟是什么意思,我该如何解决这个问题?

practice.java:13: error: incompatible types: possible lossy conversion from double to int
            pattern(t, length);
                       ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Here is my code: 这是我的代码:

public static void main(String[] args){
    Turtle t = new Turtle();
    t.delay(30);
    pattern2(t, 50.0, 3);

}

public static void pattern2(Turtle t, double length, int level){
    double random = Math.random();
    if (level == 0){
        pattern(t, length);
    } else{
        t.color(150/level, 150/level, 150/level);
        pattern2(t, length, level -1);
        t.penup();
        t.backward(length*4.5);
        t.left(60);
        t.forward(length);
        t.right(60);
        t.backward(length/random);
        t.pendown();
        pattern2(t, length/random, level-1);
    }
}

public static void pattern(Turtle t, int length){
    for (int i = 0; i < 5; i++) {
        triangle(t, length);
        t.forward(length); 
    } 
}

public static void triangle(Turtle t, int length){
    for (int i = 0; i < 3; i++) {
        t.forward(length);
        t.left(120);
    }
}

The message says when you call pattern(t, length); 当你调用pattern(t, length);时,消息会显示pattern(t, length); at line 13 you're passing it a double length when it expects an int length. 在第13行,当它需要一个int长度时,你传递一个双倍的长度。 If you change the pattern and triangle methods to take a double length instead of an int length it will fix the error. 如果您将模式和三角形方法更改为采用双倍长度而不是int长度,则会修复错误。

Edit to explicitly explain the error Your methods take an int which can only hold values up to 2^32 - 1 . 编辑以显式解释错误您的方法采用一个int,它只能容纳最多2^32 - 1 Doubles can hold values up to ~ 1.7*10^308 (See MAX_VALUE constant in Double class for more exact limit). 双精度值可以保持最大值~ 1.7*10^308 (请参阅Double类中的MAX_VALUE常量以获得更精确的限制)。 This means that a double can potentially have values (precision) that would be lost if it was used as an int. 这意味着double可能具有值(精度),如果将其用作int,则会丢失。

Your length parameter in pattern2() is double. pattern2()中的长度参数是double。 However, in pattern(), length is int. 但是,在pattern()中,length是int。 Java would not automatically convert from double to int for you. Java不会自动从double转换为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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