0
点赞
收藏
分享

微信扫一扫

Java 中奖

小北的爹 2022-08-27 阅读 60


Java 中奖_jvm

 

在游戏里,有一种宝箱,打开这个宝箱获得传奇武器的概率是

20%,现在你打开5个这样的宝箱,获得传奇武器的概率是多少?

Java 中奖_java_02

Java 中奖_servlet_03

平均值即期望,有时我们会被平均,很多样本来实验大概是每人完5次就即中奖。

public class WinngPrize {
private double chance;
private int playTime;
private int N;

public WinngPrize(double chance, int playTime, int N)
{
if( chance < 0 || chance > 1.0)
throw new IllegalArgumentException("chance must be 0 < chance < 1");

if( playTime <= 0 || N <= 0)
throw new IllegalArgumentException("playTime or N must be > 0 ");

this.chance = chance;
this.playTime = playTime;
this.N = N;
}

public void run(){

int wins = 0;

for ( int i = 0; i < N; i ++)
{
if(play())
wins ++;
}
System.out.println("winng rate:" + (double)wins/N);
}

private boolean play(){
for(int i = 0; i < playTime; i ++)
if(Math.random() < chance)
return true;
return false;
}

public static void main(String[] args) {

double chance = 0.2;
int playTime = 10;
int N = 1000000;

WinngPrize exp = new WinngPrize(chance, playTime, N);
exp.run();
}

}

 

举报

相关推荐

0 条评论