PDA

View Full Version : Using Math.random and "if, else if, else"

Collinar
11-10-2012, 03:06 PM
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?

Logic Ali
11-10-2012, 03:11 PM
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 ?

Philip M
11-10-2012, 03:15 PM
<script type = "text/javascript">

var co1 = Math.ceil(Math.random() *5); // integer 1-5
var co2 = Math.ceil(Math.random() *5);
if (co1 > co2) {
alert ("1 wins!");
}
else if (co2 > co1){
alert ("2 wins!");
}
else if (co2 == co1) {
alert ("TIE!");
}

</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.

Collinar
11-10-2012, 03:55 PM
thank you :)

Old Pedant
11-10-2012, 08:23 PM
This is wrong, Philip:

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

var co1 = 1 + Math.floor(Math.random() * 5);

Philip M
11-10-2012, 09:03 PM
This is wrong, Philip:

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

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.