3

在下面的代码中,当 x = 60 和 y = 2 时,结果 = 500。这是正确的,但 60 到 119 之间的任何 x 值给出 500。此外,当 x < 60 时,我得到除以 0 错误。此外,当 x >= 120 时,结果 = 0。我很难理解为什么会这样。我也尝试过使用 int、float 和 long 的各种组合,但仍然没有运气。

public class main {

    static long result;
    static int x;
    static int y;
    public static void main(String[] args) {
        x = 60;
        y = 2;
        result = 1000 * (1 / (x / 60)) / y;
        System.out.println(result);
    }

}

顺便说一句,我在尝试为 Android 制作节拍器应用程序时遇到了这个问题。我把这段代码脱离了上下文,以便更容易地隔离问题。非常感谢任何帮助和/或建议!

4

3 回答 3

6

答案没有错,只是不是你所期望的。您正在使用 int 除法,它将返回一个 int 结果,该结果被截断为 int 结果。

您想要进行双重除法以获得双重结果,而不是返回 int 结果的 int 除法。

// the 1.0 will allow for floating point division
result = (long) (1000 * (1.0 / (x / 60)) / y); 
于 2013-09-10T01:14:29.517 回答
1

方程可以简化为

result = 1000 * 60 / (x * y);

如果你想要浮点除法结果:

result = long(1000 * 60.0 / (x * y));

如果你想要四舍五入的浮点除法结果:

result = long(1000 * 60.0 / (x * y) + 0.5);
于 2013-09-10T01:25:48.887 回答
1

整数算术说

1999 / 100

实际上是 19,而不是您可能期望的 19.99 或 20。

如果你用整数做除法,你总是会得到实际(数学)结果的下限结果。

于 2013-09-10T01:19:11.413 回答