【问题标题】:how to use if(math.random == 50)? [closed]如何使用 if(math.random == 50)? [关闭]
【发布时间】:2019-08-24 00:16:23
【问题描述】:

所以我正在尝试创建一个选择随机数的网站,如果该数字在例如 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")
        }
    }
}

【问题讨论】:

  • 你在这里问的问题到底是什么?
  • 这样,它永远不会做任何事情,把你的代码放在opengg函数之外
  • 仅供参考:控制台日志生成一个数字,而 if 语句生成另一个数字....

标签: javascript math random


【解决方案1】:

不要使用 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();

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 2017-04-24
    • 2019-04-28
    • 2020-02-26
    • 1970-01-01
    • 2010-12-30
    • 2013-10-09
    • 2016-06-27
    • 1970-01-01
    相关资源
    最近更新 更多