LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】【サイコロ問題】関数を作成・利用し、サイコロを振った数と合計値を表示。

Last updated at Posted at 2021-05-08

<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8">
   <title>ユーザー定義関数の利点</title>
</head>
<body>
   <script>
       function throw_dice(num){
           var sum = 0;

           for (var i = 0; i < num; i++) {
               // 1以上7未満の乱数を加算する
               sum +=  Math.floor(Math.random() * 6)  +1 ;
           }
           return sum;
       }
       document.write('<p>サイコロを1個振る: ' + throw_dice(1) + '</p>');
       document.write('<p>サイコロを1個振る: ' + throw_dice(1) + '</p>');
       document.write('<p>サイコロを2個振る: ' + throw_dice(2) + '</p>');
       document.write('<p>サイコロを2個振る: ' + throw_dice(2) + '</p>');
       document.write('<p>サイコロを3個振る: ' + throw_dice(3) + '</p>');
       document.write('<p>サイコロを3個振る: ' + throw_dice(3) + '</p>');
   </script>
</body>
</html>

image.png

Math.random() * 6 で 0以上61未満の整数が得られる。

sum +=  Math.floor(Math.random() * 6) ;

↓それに1を加えているので、「1以上7未満」の範囲の整数が得られるわけです。
つまり1〜6のサイコロで出来上がり

sum +=  Math.floor(Math.random() * 6) + 1 ;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0