首页 > 解决方案 > 如何使用 if(math.random == 50)?

问题描述

所以我正在尝试制作一个选择随机数的网站,如果该数字在例如 50-60 之间,它将会做一些事情

这是一些代码:

var opengg;
window.onload = function() {
    opengg = function() {
    console.log(Math.floor(Math.random() * 100));
    if (Math.floor(Math.random() * 100) == 50) {
            console.log("test")
        }
    }
}

标签: javascriptmathrandom

解决方案


不要使用Math.floor(Math.random() * 100)两次,而是只使用一次,因为每次它都会生成一个新数字并将其分配给一个变量并检查它是否在 50 和 60 之间。Math.floor(Math.random() * 100)内部console.log();&的结果if ()不太可能相等。因此,即使您看到数字日志在范围内,但在if的条件语句中很少会是相同的数字

let opengg = function() {
  let num = Math.floor(Math.random() * 100);
  console.log(num)
  if (num >= 50 && num <= 60) {
    console.log("test")
  }
}

opengg();


推荐阅读