日常場景:某活動抽獎,控制各等獎的出現概率
比如控制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) +"%"); } } }
結果為:
========《無律》==========