-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