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

1. ## 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 :

<SCRIPT language = "JavaScript">

//generate a random number greater than or equal to 0.0 and less than 50.0
//and display it in an alert dialogue

</SCRIPT>
<BODY>
<STRONG>A test of the random number functions <BR></STRONG>
<FORM NAME = "randomForm">

<INPUT TYPE = "button" NAME = "randomButton" VALUE ="Display Random Number"
</FORM>

can anyone advise me where I would put the Math.round function and how to make it work ?

• Sounds like homework.

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

function getRoundedRandomNumber(num) {
var randy = Math.floor(Math.random() * num +1);
}

</script>

<strong>A test of the random number functions <br></strong>

<input type = "button" name = "randomButton" value ="Display Random Number" onclick = "getRoundedRandomNumber(50);">```
<script language=javascript> is long deprecated and obsolete. Use <script type = "text/javascript"> instead.

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:-
http://www.shawnolson.net/a/789/make...om-useful.html

Note the difference between
var randy = Math.floor(Math.random() * num +1); // gives 1 to num
and
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.

• ## Users who have thanked Philip M for this post:

oceanic (09-02-2009)

•