-4
我正在尝试创建一个有趣的概率计算器,但由于某些原因,java在分割两个数字时得到了错误的答案。这里是我的代码....为什么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应该是51.4(千分之五百十四* 100 d是0, )。这是为什么发生?
不要这样做... – Thomas
重复[* Java Division error *](http://stackoverflow.com/questions/10376322/java-division-error)(在A的前四个命中内众所周知的搜索引擎)以及约150个其他搜索引擎。发帖前请先搜索。 –
@Thomas作为托儿教师https://www.youtube.com/watch?v=ZXhHFgDRNBQ(约40秒钟),我不禁听到乔伊斯格伦费尔的声音“不要那样做”。 – Jaydee