从.5到正常方式的双向整数 [英] Double to int rounding normal way from .5

查看:98
本文介绍了从.5到正常方式的双向整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行计算,为此我使用以下表达式:

I'm making calculation and for that I'm using the following expression:

Player.targetx = (int) (((e.getX() - Frame.x)/(Screen.myWidth/World.worldWidth))-8);

例如:

如果值是(((103 - 40)/(1184/15)) - 8)双重答案在 -7.20186 。 Player.targetx 仍然获得 -8 的价值。

if the values are (((103 - 40)/(1184/15))-8) the double answer is around -7.20186. Player.targetx still gets value of -8.

为什么?我想这样做 -7.5 给我回答 -8 以及 -7,49999 9给出 -7 的答案。

Why's that? I would like to make it so that -7.5 gives me answer of -8 and anything like -7,499999 gives answer of -7.

推荐答案

转换为 int 始终截断为0.要 round ,您可以使用 Math.round () 。但是,它总是向上舍入向上

Casting to int always truncates towards 0. To round, you can use Math.round() instead. However, that always rounds halves up:

class Test {
    public static void main(String[] args) {
        System.out.println(Math.round(-7.7)); // -8
        System.out.println(Math.round(-7.5)); // -7
        System.out.println(Math.round(-7.2)); // -7

        System.out.println(Math.round(+7.2)); // 7
        System.out.println(Math.round(+7.5)); // 8
        System.out.println(Math.round(+7.7)); // 8
    }
}

你确定要圆半远离零?如果是这样, Math.round()将不会完全按照您的意愿行事。你可以编写自己的方法:

Are you sure you want to round halves away from zero? If so, Math.round() won't quite do what you want. You could write your own method though:

public static long customRound(double x) {
    return x >= 0 ? (long) (x + 0.5)
                  : (long) (x - 0.5);
}

这将始终从零开始,先加上或减去0.5(取决于符号)然后截断为0.这产生与以前相同的值,除了-7.5舍入到-8。

This will always round away from zero, by either adding or subtracting 0.5 first (depending on the sign) and then truncating towards 0. That produces the same values as before, except that -7.5 is rounded to -8.

编辑:我怀疑剩下的问题几乎可以肯定是由于整数运算中的除法。我们不知道你的任何值的类型,但我怀疑它们都是 int ,这会导致这个问题。如果您使用除法 double 之一的操作数,它将在 double 算术中执行除法。最简单的方法 - 这也会增加可读性 - 可能是提取一些表达式来分隔变量,并在必要时进行投射:

I suspect the remaining problem is almost certainly due to the division being performed in integer arithmetic. We don't know the types of any of your values, but I suspect they're all int, which would lead to that problem. If you make either of the operands of the division double, it will perform the division in double arithmetic instead. The easiest way to do that - which would also increase readability - is probably to extract some of the expressions to separate variables, and cast where necessary:

double xDifference = e.getX() - Frame.x;
double widthRatio = Screen.myWidth / (double) World.worldWith;
double x = (xDifference / widthRatio) - 8;
Player.targetx = (int) Math.round(x);

如果仍然不起作用,至少你会更容易看到什么是错的。

If that still doesn't work, at least you'll have a much easier time seeing what's wrong.

这篇关于从.5到正常方式的双向整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆