【问题标题】:Slaying the Dragon JS屠龙JS
【发布时间】:2017-03-18 17:36:51
【问题描述】:

我被分配编写以下代码:

var slaying = true;
var youHit= Math.floor(Math.random()*2); 
var damageThisRound = Math.floor(Math.random()*5);  
var totalDamage = 3; 

while (slaying){
   
    if(youHit === 1){
        console.log("Congratulations!, You hit your first Dragon.");
        totalDamage += damageThisRound;
        if(totalDamage >= 4){
                console.log('You slew the dragon'); 
            }else if(totalDamage < 4){
                youHit = Math.floor(Math.random()*2);
                }
        slaying = false;
        }else if(youHit === 0){
            console.log("Try again, the dragon defeated you");
             slaying = false;
            }
    
    }

这段代码运行,但最后我得到一个 False 的输出,

有人可以帮我理解这是否来自 slaying 变量,或者这是否是 if 语句之一的结果?我不明白它为什么会出现在控制台上。

提前致谢。

【问题讨论】:

  • 你的例子似乎有效。
  • 如果你想理解这段代码,你可能应该去看看这被撕掉的 codecademy 教程:codecademy.com/courses/javascript-beginner-en-mrTNH-6VIZ9/0/…
  • @Cole9350 感谢您的回复。这是代码学院的一项任务,我对此进行了编码,但仍需要一些说明。感谢您的建议。

标签: javascript variables while-loop boolean


【解决方案1】:

代码返回true还是false取决于这行代码:

var youHit= Math.floor(Math.random()*2); 

Math.random() 得到一个介于 0 和 1 之间的随机数。如果随机数大于 0.5,则为真,否则为假。此代码每次运行时都会随机选择一个数字。您可以通过设置来验证这一点:

var youHit = .9

var youHit = .1

【讨论】:

    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多