Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
09-02-2009, 01:03 PM #1
- Join Date
- Sep 2009
- North West UK
- Thanked 0 Times in 0 Posts
Help needed with code for program please
Hi I am new to programming and I am trying to write a piece of code, I need the output to be a whole random number, this is what I have up to now :
//generate a random number greater than or equal to 0.0 and less than 50.0
//and display it in an alert dialogue
window.alert("getRoundedRandomNumber: " Math.round + Math.random()*50);
<STRONG>A test of the random number functions <BR></STRONG>
<FORM NAME = "randomForm">
<INPUT TYPE = "button" NAME = "randomButton" VALUE ="Display Random Number"
ONCLICK = "window.alert(getRoundedRandomNumber(50));">
can anyone advise me where I would put the Math.round function and how to make it work ?
Thanks in advance
09-02-2009, 01:51 PM #2
- Join Date
- Jun 2002
- London, England
- Thanked 2,538 Times in 2,516 Posts
Sounds like homework.
Use lowercase for tags - <script>, <input> etc.
Math.round() does not produce true random numbers. In this case the numbers 0 and 50 will be chosen less frequently. Other numbers in the range can be arrived at by rounding up or by rounding down - but 50 can only be arrived at by rounding up, and 0 only by rounding down. Use instead Math.floor(Math.random() * num +1). If you want another explanation see:-
Note the difference between
var randy = Math.floor(Math.random() * num +1); // gives 1 to num
var randy = Math.floor(Math.random() * (num +1)) // gives 0 to num
BTW, the time to say "thanks" is afterwards, not beforehand which gives the - doubtless unintended - impression that you take other people's voluntary unpaid assistance for granted. Or as British politician Neil Kinnock put it, "Don't belch before you have had the meal." Prefer to use "please" beforehand and if you find a response helpful then you can use the "Thank User For This Post" button.
Last edited by Philip M; 09-02-2009 at 04:07 PM.
Users who have thanked Philip M for this post: