2015-05-29 52 views
-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, )。這是爲什麼發生?

+4

不要這樣做... – Thomas

+1

重複[* Java Division error *](http://stackoverflow.com/questions/10376322/java-division-error)(在A的前四個命中內衆所周知的搜索引擎)以及約150個其他搜索引擎。發帖前請先搜索。 –

+1

@Thomas作爲托兒教師https://www.youtube.com/watch?v=ZXhHFgDRNBQ(約40秒鐘),我不禁聽到喬伊斯格倫費爾的聲音「不要那樣做」。 – Jaydee

回答

1

y/numLoops將是一個整數,因爲這兩個參數都是整數。改爲嘗試(double)y/numLoopsy/(double)numLoops

如果分解double d = (y/numLoops) * 100;你會得到類似的步驟東西:

  • int r = y/numLoops; - 根據有兩個整數操作數的運算將有int結果的規範。
  • double d = r * 100此處r將爲0,因爲是int
+0

是的,這工作。謝謝 –

相關問題