我试图创建一个有趣的概率计算器,但由于某种原因,当我分割两个数字时,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)时。为什么会这样?
答案 0 :(得分:1)
y/numLoops
将是一个整数,因为两个参数都是整数。请改为(double)y/numLoops
或y/(double)numLoops
。
如果您分解double d = (y/numLoops) * 100;
,您将获得与这些步骤类似的内容:
int r = y/numLoops;
- 根据规范,具有两个整数操作数的操作将产生int
结果。double d = r * 100
此处r由于为int
而为0。