【问题标题】:Possible loss of precision / [type] cannot be dereferenced可能的精度损失/[类型]不能被取消引用
【发布时间】:2010-05-20 12:29:47
【问题描述】:

我已经环顾四周,但我根本找不到一个好的解决方案......

Point mouse = MouseInfo.getPointerInfo().getLocation();

int dx = (BULLET_SPEED*Math.abs(x - mouse.getX()))/
                    (Math.abs(y - mouse.getY()) + Math.abs(x - mouse.getX()))*
                    (x - mouse.getX())/Math.abs(x - mouse.getX());

在这个星座中,我得到:可能的精度损失,当我将 (x - mouse.getX()) 更改为 (x - mouse.getX()).doubleValue() 时,它说 double 不能被取消引用,当我在某处添加 intValue() 时它说 int 不能被取消引用。我的错误是什么?

[x, y 是整数 | BULLET_SPEED 是static final int]

谢谢!

【问题讨论】:

    标签: java integer double


    【解决方案1】:

    我会将 xyBULLET_SPEED 存储为双精度,以双精度执行所有算术运算,然后作为最后一步转换为 int。

    【讨论】:

    • 是的,我正在考虑,但我必须将所有函数的所有参数从 int 更改为 double than,因为 x 和 y 被广泛使用
    • 或者将 double_x 和 double_y 局部变量添加到函数中并对其进行算术运算。
    【解决方案2】:

    只需使用(int) 投射

    int i = (int) 3.14159; // compiles fine
    

    这不会避免任何精度损失,但它会向编译器明确表明这是您想要的,因此代码会编译。

    请记住投射的优先级。

    int i = (int) .1D + .1D; // doesn't compile!!!
    int j = (int) (.1D + .1D); // compiles fine
    

    相关问题


    关于取消引用错误

    基元不是对象;他们没有成员。

        Integer ii = 42; // autoboxing
        int i = ii.intValue(); // compiles fine
        int j = i.intValue(); // doesn't compile
    

    另见


    所以在这种特定情况下,您可以执行以下操作:

    int dx = (int) (BULLET_SPEED*Math.abs(x - mouse.getX()))/
                    (Math.abs(y - mouse.getY()) + Math.abs(x - mouse.getX()))*
                    (x - mouse.getX())/Math.abs(x - mouse.getX());
    

    【讨论】:

    • @Samuel:查看最新版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2021-09-26
    • 2019-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多