2015-09-27 136 views
-1

在我的代码,我有一个行的代码,使不同的NaN这个神秘的结果,总是:为什么是减法的结果等于为NaN

console.log("The dragon now has"+ (4-totalDamage) + "health left!") 

现在totalDamage等于给自己加了一个名为damageThisRound变量,这是一个从1到5的随机整数(也包括1和5)。现在,我希望这条线来记录一些像:

The dragon now has 1 health left! 

,而是,我得到:

The dragon now has NaNhealth left! 

为什么结果等于为NaN,而不是像1,2或3的整数(这应该是(4-totalDamage)唯一可能的结果)?

全码:

var slaying = true 
var youHit = Math.floor(Math.random()*2) 
var damageThisRound = Math.floor(Math.random*5 + 1) 
var totalDamage = 0 

while (slaying) { 
    if (youHit) { 
     console.log("You hit the dragon!"); 
     totalDamage += damageThisRound; 
     if (totalDamage >= 4) { 
      console.log("You defeated the mighty dragon!"); 
      slaying = false; 
     } else { 
      console.log("The dragon now has"+ (4-totalDamage) + "health left!") 
      youHit = Math.floor(Math.random() * 2); 
     } 
    } else { 
    console.log("You lose!"); 
    slaying = false; 
    } 
} 
+1

请显示完整的代码示例,以便我们可以重现该问题。具体说明'totalDamage'是如何设置的。 – j08691

+2

totalDamage可能是字符串格式。尝试:'4-parseInt(totalDamage)'(并且确保totalDamage并非已经是NaN,与以前的随机数相加) – dievardump

+0

'totalDamage'是'NaN'或不能转换为有效数字。提供一个完整的示例。 –

回答

3

通过var damageThisRound = Math.floor(Math.random()*5 + 1)

更换var damageThisRound = Math.floor(Math.random*5 + 1)你打电话Math.random()时忘了()

Math.random*5NaN 然后damageThisRoundNaN等为totalDamage,因为你尝试添加NaN它。