How can I make Delphi 2 pick me any number within a range I specify (for example, between 0 and 100)?I’m guessing this is a fairly easy thing to do, but I couldn’t find it in the manual…
To get Delphi to pick any number within a specific range, you use thebuilt-in random number generator. Here’s a quick function to get you on yourway:
function GetRandomInt(UpperRange : Integer) : Integer;begin Randomize; Result := Random(UpperRange);end;To get any number between 0 and 100, you’d call
GetRandomInt, like so:
RandInteger := GetRandomInt(100);So what’s going on in the code? The first line, Randomize, initializesDelphi’s random number generator. Then the second call, using theRandom function, sets the function’s result to a number between 0and the
A quick note about the Random function: It’s one of the very fewfunctions in Delphi that can be overloaded; that is, you can have a variablenumber of parameters. With Random, it’s either no parameters or an upperrange. If you don’t specify any parameters with Random (i.e. just declareRandom;) the function will return a Real number between 0 and 1. If youspecify an upper-range parameter, Random will return an integer between 0and the upper range.
You might be thinking, “Wait a minute! I thought Delphi didn’t support variable parameters otherthan open arrays.”
It doesn’t. But there are certain functions built into theDelphi engine that can take variable numbers of parameters. Random is one ofthem, and off the top of my head, I can’t name others. In any case, playaround with this. For another reference, look up Random in the help file.