【问题标题】:How to generate a random number only once, and reuse its output?如何只生成一次随机数,并重用其输出?
【发布时间】:2014-07-25 16:30:08
【问题描述】:

我从 Javascript 开始学习编程,我的老师让我们随机掷骰子,一个简单的 Math.ceil(6*Math.random())

我试图稍微游戏化它并判断结果。所以,如果你掷出 7,你就赢了,任何其他掷出你就输了。最终的结果是,

"你投了一个:7 你赢了!”

但是,我试图通过大致说来完成:

console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose.  Better luck next time");

}

diceSum() 函数每次都会计算,所以我可能会得到“你投了一个:7”和“Aw...你输了”,因为第一次投出的是 7,但是当 if 语句进入时, diceSum 是不同的东西。

如何像掷骰子一样生成一个随机数,然后一遍又一遍地重复使用它的值?

这是我当前的代码(这远远超出了必要的范围,因为我正在尝试显示这些值,所以我知道它是否返回了正确的答案):

//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
    return Math.ceil(6*Math.random());
};

//Sum up two dice rolls
var diceSum = function() {
   var firstDie = getDieRoll();
   var secondDie = getDieRoll();
   return firstDie+secondDie;
};
//

//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose.  Better luck next time."
//

//Outputs
//show total sum to compare with message below
console.log(diceSum())

//Return a message stating the result
console.log("You rolled a " + diceSum())

//View true false status to compare with message returned below
console.log(diceSum()==7)

//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){ 
console.log(winMsg);
 } else {
console.log(loseMsg);
}

【问题讨论】:

  • 分离出逻辑。例如,有一个掷骰子并存储结果的函数,以及一个返回结果的函数。或者,一个新对象调用:启动“骰子事务”、“向运行总和添加新骰子”、“返回运行总和”和“结束事务”。
  • 您显示的代码过于集成。将其拆分为逻辑部分,然后组合这些部分——可能然后依次组合这些部分。
  • 我相信你要找的是一个变量。

标签: javascript node.js random


【解决方案1】:

您将结果放入变量中,并使用该变量:

var sum = diceSum();

//Outputs
//show total sum to compare with message below
console.log(sum);

//Return a message stating the result
console.log("You rolled a " + sum)

//View true false status to compare with message returned below
console.log(sum == 7);

//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){ 
  console.log(winMsg);
} else {
  console.log(loseMsg);
}

顺便说一下,计算随机数的方法是错误的。 random method 被定义为返回一个 0

如果使用Math.ceil,效果是结果偶尔会为零,得到六的机会比其他数字略小。

改用Math.floor

function getDieRoll() {
  return Math.floor(6 * Math.random()) + 1;
};

【讨论】:

    【解决方案2】:

    将其保存到变量中:

    var sum = diceSum();
    
    console.log("You rolled a " + sum);
    
    if (sum == 7) { 
        console.log(winMsg);
    } else {
        console.log(loseMsg);
    }
    

    或者:

    var sum = diceSum(),
        msg = sum == 7 ? winMsg : loseMsg;
    console.log("You rolled a " + sum);
    console.log(msg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 2023-01-03
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多