2017-06-17 7 views
-2

私はcodecademyでDragon Slayer Interactiveアクティビティを完了しました。私は "Math.floor(Math.random()* 2);"そうするはずです。ドラゴンスレイヤー - Math.floor(Math.random()* 2)の意味は?

私の "Dragon Slayer!"対話型活動の完全なコードはここにあります。

var slaying = true; 
var youHit = Math.floor(Math.random() * 2); 
var totalDamage = 0; 
while (slaying) { 
    var damageThisRound = Math.floor(Math.random() * 5 + 1); 
    if (youHit) { 
    console.log(“You hit the dragon!”); 
    totalDamage += damageThisRound; 
    if (totalDamage >= 4) { 
     console.log(“You slew the dragon!”); 
     slaying = false; 
    } else { 
     youHit = Math.floor(Math.random() * 2); 
    } 
    } else { 
    console.log(“The dragon defeated you!”); 
    slaying = false; 
    } 
} 

Math.floor(Math.random()* 2)の機能は何ですか?

+1

ランダムに番号「0」または「1」のいずれかを生成します。 'Math.random()'がどのように動作するかを調べることをお勧めします。 – abhishekkannojia

+0

キャメロンを覚えている**本当の**ドラゴンスレイヤー**は彼の質問を適切にフォーマットして、みんながあなたの** [MCVE](https://stackoverflow.com/help/mcve)**を簡単に読むことができるようにします。奴隷化し続ける! – iamdanchiv

+2

[Concept of Math.floor(Math.random()\ * 5 + 1)の可能な複製は、真の範囲とその理由は何ですか?](https://stackoverflow.com/questions/21483667/concept-of-math) -floormath-random-5-1-真実の範囲と理由) –

答えて

0

he Math.random()関数は、[0、1)の範囲の浮動小数点擬似乱数を返します。つまり、0(包括)から1(除外)までは含まれません。これを使用して、希望する範囲に拡大することができます。実装は、乱数生成アルゴリズムの初期シードを選択します。ユーザーが選択またはリセットすることはできません。

Math.floor()関数は、指定された数以下の最大の整数を返します。

Math.floor(45.95); // 45 
Math.floor(45.05); // 45 
Math.floor( 4 ); // 4 
Math.floor(-45.05); // -46 
Math.floor(-45.95); // -46 

Math.random(); // 0.7757860020429985 
Math.random() * 2 // number from range 0.x to 1.x 

Math.floor(Math.random() * 2); // will give from 0 or 1 
+0

ねえ、ありがとう。私はなぜmath.floor(45.95)という理由でちょっと混乱しました。 45を与えていない46 –

+0

@CameronSu Math.floorは答えで見られるように正の値のラウンドを実行しないので、別のメソッドの数を切り捨てる方法はmath.ceilが丸めを行うmath.ceil(45.95)= > 46 –