为什么java没有正确地进行数学运算

时间:2015-05-29 08:37:56

标签: java math

我试图创建一个有趣的概率计算器,但由于某种原因,当我分割两个数字时,java会得到错误的答案。这是我的代码......

import javax.swing.JOptionPane;

public class ProbabilityCalculator {
public static void main(String args[]) {
    String a = JOptionPane.showInputDialog("One out of.....");
    int x = Integer.parseInt(a);
    int numLoops = 1000;
    int y = 0;
    int n = 0;
    for (int i = 0; i < numLoops; i++) {
        int result = (int) (Math.random() * x + 1);
        int result2 = (int) (Math.random() * x + 1);

        if (result == result2)
            y++;
        else
            n++;
    }
    System.out.println(y);
    System.out.println(numLoops);
    System.out.println(y/numLoops);


    double d = (y/numLoops) * 100; //get it? double d??
    JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
            + y + " times it worked, while " + n + " times it didn't.");
    JOptionPane.showMessageDialog(null, "Your percentage was " + d
            + "%.");
    System.exit(0);
    }
}

当我运行此代码一次时,y为514,numLoops为1000,但d为0,当d应为51.4(514/1000 * 100)时。为什么会这样?

1 个答案:

答案 0 :(得分:1)

y/numLoops将是一个整数,因为两个参数都是整数。请改为(double)y/numLoopsy/(double)numLoops

如果您分解double d = (y/numLoops) * 100;,您将获得与这些步骤类似的内容:

  • int r = y/numLoops; - 根据规范,具有两个整数操作数的操作将产生int结果。
  • double d = r * 100此处r由于为int而为0。