user2395715
user2395715

Reputation: 85

How to randomly generate numbers?

I'm new to javascript and am trying to write a script that will randomly select a number between 1 and 100 and then print each number up to but not including the random integer, except for special cases like 50 in which it prints fifty. So for instance, if it the random integer is 10, it would print 1-9. I've got the first part down but the issue I'm having is how to set the limit on how many numbers will print and how I stop it from writing the random integer as well. Currently, this code will randomly print an infinite amount of numbers and I want it to be no higher than 100. Any ideas? Thanks!

<!DOCTYPE html>
<html>
<head>
    <title>Random Number</title>
    <meta charset="utf-8">
    <script>
        var newNumber ="";
        for( var i=1; (Math.floor(Math.random()*100)); i++) {


            if (i==50) {
                newNumber += "fifty ";

            }
            else {
                NewNumber += i + " ";
            }

        }
        document.write(newNumber);

    </script>
</head>
<body>          
</body>
</html>

Upvotes: 1

Views: 110

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

In the for loop, you need to specify the condition properly, like this

for(var i = 1, randMax = (Math.floor(Math.random()*100)); i < randMax; i++) {

Here, we generate the random number only once, at the beginning of the for loop and we make sure that, we don't execute the loop more than the random maximum number.

Upvotes: 2

Related Questions