zoukankan      html  css  js  c++  java
  • 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) +"%");
        }
        }
    
    }

    结果为:

    ========《无律》==========

  • 相关阅读:
    java图片加文字
    [转]NetBeans优化技巧 提升启动速度
    重建win7桌面图标缓存
    负载测试(Load Test)
    乐观锁与悲观琐的区别
    事物锁表问题
    建立silverlight安装环境
    持续集成ccnet
    C# AppDomain
    Windows Services
  • 原文地址:https://www.cnblogs.com/zz-3m23d-begining/p/7767214.html
Copyright © 2011-2022 走看看