Jump to content

Simple code is behaving oddly...


ShootingBlanks

Recommended Posts

Hello.  Please note the following code, placed on its own between the BODY tags of a webpage:

<script type="text/javascript">
var outputNumber;
var numbersGenerated;
var startNumber = prompt("Pick a number to start with","");
var endNumber = prompt("Pick a number to end with","")
var numberCount = prompt("How many random numbers would you like generated?","");
var numberDifference = Math.abs(endNumber-startNumber);

for (numbersGenerated = 0; numbersGenerated < numberCount; numbersGenerated++) {
outputNumber = (Math.floor(Math.random() * numberDifference) + 50);
document.write(numbersGenerated+1 + ". " + outputNumber + "<br />");
}
</script>

 

Enter "50" in the first prompt, then "75" in the second, then "50" in the third.  The code seems to work as I'd like (showing 50 random numbers bewtween 50 & 75)...

 

NOW, go ahead and change this line:

outputNumber = (Math.floor(Math.random() * numberDifference) + 50);

To this:

outputNumber = (Math.floor(Math.random() * numberDifference) + startNumber);

 

And the code totally messes up.  But "startNumber" IS "50", so I'm not understanding why changing it from a number to a variable would yield such different results!...

 

Link to comment
https://forums.phpfreaks.com/topic/72657-simple-code-is-behaving-oddly/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.