Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Using Math.random and "if, else if, else"

1. ## Using Math.random and "if, else if, else"

I tried writing a program using Math.random and if, else if and else...
This is what I wrote:

var co1 = Math.random(1, 5);
var co2 = Math.random(1, 5);
if (co1 > co2){
console.log("1 wins!");
}
else if (co2 > co1){
console.log("2 wins!");
}
else co2 === co1;
console.log("TIE!")

Now when I run it, I always get "1 wins!" or "2 wins!" and a "TIE!".
for example:
Running:
1 wins!
TIE!
Running:
2 wins!
TIE!

Why is this happening? And how could I stop the Tie from being written without deleting it completly from the program?

2. Originally Posted by Collinar
This is what I wrote:

var co1 = Math.random(1, 5);
var co2 = Math.random(1, 5);
What documentation did you read to get the usage of Math.random ?

3. Code:
```<script type = "text/javascript">

var co1 = Math.ceil(Math.random() *5);  //  integer 1-5
var co2 = Math.ceil(Math.random() *5);
if (co1 > co2) {
}
else if (co2 > co1){
}
else if (co2 == co1)  {
}

</script>```
console.log("TIE!") says do just that. It is not contained within an if/else clause.

When the questions are being asked, that's when you come up with the answers.

4. thank you

5. This is wrong, Philip:
Code:
`var co1 = Math.ceil(Math.random() *5);`
There is a vanishingly small but still finite chance that Math.random() can return a value of ZERO.

And so on those (admiittedly very rare) occasions when it does so, Math.ceil(0) is 0 and you get a number outside the desired range.

To avoid even a *chance* of that happening you really should do
Code:
`var co1 = 1 + Math.floor(Math.random() * 5);`

6. Originally Posted by Old Pedant
This is wrong, Philip:
Code:
`var co1 = Math.ceil(Math.random() *5);`
There is a vanishingly small but still finite chance that Math.random() can return a value of ZERO.

And so on those (admiittedly very rare) occasions when it does so, Math.ceil(0) is 0 and you get a number outside the desired range.

To avoid even a *chance* of that happening you really should do
Code:
`var co1 = 1 + Math.floor(Math.random() * 5);`
Yes, you are quite right. As you say, a vanishingly small chance but still possible to return zero. But that would not affect this particular script, even if zero came up.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•