Dan
Dan

Reputation: 343

random number between 0 - 8 JavaScript

I am trying to generate 40 random numbers between 0 to 8

This is my code --

<body>
    <h1>This is a page for randomize number between 0 - 8 </h1> <br />

<button onclick="randomize()">Random number</button>

<p id="Output"></p>

<script>
function randomize() {

    var arr = []
while(arr.length < 40){
  var randomnumber=Math.floor((Math.random() * 8) + 1)
  arr.push(randomnumber) 
}
document.getElementById("Output").innerHTML = arr;
}
</script> 
</body>

I am expecting 40 random numbers to be Output like --

4
4
5
7
8
1
5
7

What I am doing wrong can someone correct me please and also I want the result to be outputted by the next line !

Can someone help !

Upvotes: 2

Views: 8097

Answers (3)

Ties
Ties

Reputation: 805

Your code already works, just ad line breaks:

<body>
<h1>This is a page for randomize number between 0 - 8 </h1> <br />

<button onclick="randomize()">Random number</button>

<p id="Output"></p>

<script>
function randomize() {

    var arr = []
    while(arr.length < 40){
        var randomnumber=Math.floor((Math.random() * 9)) // 0-8 is 9 numbers
        arr.push(randomnumber) 
    }
    document.getElementById("Output").innerHTML = arr.join('<br>'); // Add line break between numbers

}
</script> 
</body>

EDIT: changed random multiplier from 8 to 9

Upvotes: 2

Keiran Tai
Keiran Tai

Reputation: 962

I think you need to look into your random calculation and use .join() to make the number in separate lines.

1) The random formulate should be Math.floor(Math.random()*(1+High-Low))+Low;. Since you multiply Math.random() with 8, you will only get 7 as maximum. However you're adding +1 after random, you will still get 8 as maximum number but the minimum becomes 1. You're genearating 1 to 8 now.

2) If you need to echo each number in a new line, you need to join the array with <br/>. E.g. document.getElementIdBy('Output').innerHtml = arr.join('<br/>').

Upvotes: 1

Amadan
Amadan

Reputation: 198314

a) If you multiply by 8, you are getting numbers from 0 to 7.

b) .innerHTML = arr.join('<br>') should give you the output you want.

Upvotes: 1

Related Questions