实现要骰子的函数(其中1,2,3,4,5的概率为10%,6的概率为50%)?
思路:利用随机数,取1-10个数,每个数字的出现概率是10%,1,2,3,4,5,5个数各输出1,2,3,4,5;6-10,5个数,输出6
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一道概率问题的面试题</title>
</head>
<body>
<script type="text/javascript">
function ranFn() {
var ranNum = Math.floor(Math.random() * 10 + 1);
if(ranNum == 1) {
return 1;
};
if(ranNum == 2) {
return 2;
};
if(ranNum == 3) {
return 3;
};
if(ranNum == 4) {
return 4;
};
if(ranNum == 5) {
return 5;
};
if(ranNum > 5 && ranNum < 11) {
return 6;
};
}
var ranVal = ranFn();
console.log(ranVal)
</script>
</body>
</html>