Page 1 of 1

subroutine for adding random generated numbers

Posted: Mon Feb 25, 2008 6:15 pm
by Sgledhill5
Are there any Qbasic Programmers who can provide me with a subroutine for adding random generated numbers, thanks

Re: subroutine for adding random generated numbers

Posted: Mon Feb 25, 2008 8:22 pm
by moneo
Sgledhill5 wrote:Are there any Qbasic Programmers who can provide me with a subroutine for adding random generated numbers, thanks
DECLARE FUNCTION RandInt% (Lower, Upper)
RANDOMIZE TIMER 'Put this at the top of your program to seed the RND function.


' =============================== RandInt% ===================================
' Returns a random integer greater than or equal to the Lower parameter
' and less than or equal to the Upper parameter.
' ============================================================================
'
FUNCTION RandInt% (Lower, Upper) STATIC
RandInt% = INT(RND * (Upper - Lower + 1)) + Lower
END FUNCTION


NOTES AND QUESTIONS:
1) The above function will work easier than a subroutine.

2) The way the function is set up, the maximum random number is 32767, that is, an integer.

3) You will need to set up the Lower and the Upper parameters.

4) How do you want to handle duplicate random numbers, process them or eliminate them?

5) What do you mean by ADDING random generated numbers? Adding them together, adding them to an array?

Regards..... Moneo

Try calling that!

Posted: Tue Feb 26, 2008 1:03 am
by burger2227
To create a Random number, you just use RND. But you have to set the number limits first.

RND returns a number from 0 to .9999999 by itself. That is not a great range of numbers.

So now you have to set a maximum number by multiplying the RND by the maximum number needed. Most times you need an Integer answer so you get the result using the INT() function. There is a problem there, because value = INT(RND * 65) will never give you 65.

Adding 1 to the equation creates numbers from 1 to 65.

To get values from 0 to 65 you need to multiply by 66 using INT. The value cannot be the maximum when INT is involved because it rounds down. You could use CINT or CLNG to round to the closest number.

To create really random numbers, use RANDOMIZE TIMER before using RND. Otherwise, QB will always send the same sequence of numbers everytime the program is run. The TIMER seeds the RND sequence to the actual second of the day. That is 86400 different seeds!

Ted