在Java中执行计算会给出完全错误的答案 [英] Performing a calculation in Java gives completely wrong answer

查看:78
本文介绍了在Java中执行计算会给出完全错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the code below, when x = 60 and y = 2, result = 500. This is correct, but any x value between 60 and 119 also gives 500. Also, when x < 60, I get a divide by 0 error. Additionally, when x >= 120, result = 0. I am stumped as to why this is happening. I have also tried using various combinations of int, float, and long and still, no luck.

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制作节拍器应用程序时出现问题。我将此代码脱离了上下文,以便更容易隔离问题。任何帮助和/或建议都非常感谢!

By the way, I encountered this problem while trying to make a metronome application for Android. I took this code out of context to make it easier to isolate the problem. Any help and/or suggestions are very appreciated!

推荐答案

答案没有错,这不是你所期待的。你正在使用int division,它将返回一个int结果,结果被截断为int结果。

The answer is not wrong, it's just not what you're expecting. You're using int division which will return an int result, a result that is truncated to the int result.

你想做双重除法得到一个双重结果, not int division返回int结果。

You want to do double division to get a double result, not int division which returns an int result.

// the 1.0 will allow for floating point division
result = (long) (1000 * (1.0 / (x / 60)) / y); 

这篇关于在Java中执行计算会给出完全错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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