JAVA概率實現--一篇最常見、最通用解決方案


日常場景:某活動抽獎,控制各等獎的出現概率

比如控制A(中獎率):20%;B(獲得優惠券率):30%;C(謝謝參與率):50%

下面以封裝好在main()函數里,上代碼(記得導入相應的包):

public class Probability {
    public static void main(String[] args) {/**
     * 先來一個簡單通用的解決方案
     * 需求:生成A(一等獎):20%;B(二等獎):30%;C(不中獎):50%
     */
    double num;
    Map<String ,Integer> confirmMap = new HashMap<>();
    int countA = 0;
    int countB = 0;
    int countC = 0;
    for(int i = 0; i < 10000; i++){
        num = Math.random() * 100;
        if(num < 20){
        countA++;
        }else if(num >= 20 && num < 50){
        countB++;
        }else{
        countC++;
        }
    }
    confirmMap.put("A", countA);
    confirmMap.put("B", countB);
    confirmMap.put("C", countC);
    int total = 0;
    for(Map.Entry<String, Integer> cmap : confirmMap.entrySet()){
        total += cmap.getValue();
    }
    System.out.println("總計:"+total);
    NumberFormat nfmt = NumberFormat.getInstance();// 創建一個數值格式化對象  
    nfmt.setMinimumIntegerDigits(2);// 設置精確到小數點后2位 
    for(Map.Entry<String, Integer> omap : confirmMap.entrySet()){
        System.out.print(omap.getKey()+":"+omap.getValue());
        System.out.println("。。。占比為" + nfmt.format((double)omap.getValue()/total * 100) +"%");
    }
    }

}

結果為:

========《無律》==========


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM