TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

Language: Pascal
Expertise: Beginner
Jul 23, 1997

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# Pick-a-number?

Question:
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 the built-in random number generator. Here's a quick function to get you on your way:

```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, initializes Delphi's random number generator. Then the second call, using the Random function, sets the function's result to a number between 0 and the `UpperRange` specified.

A quick note about the Random function: It's one of the very few functions in Delphi that can be overloaded; that is, you can have a variable number of parameters. With Random, it's either no parameters or an upper range. If you don't specify any parameters with Random (i.e. just declare Random;) the function will return a Real number between 0 and 1. If you specify an upper-range parameter, Random will return an integer between 0 and the upper range.

You might be thinking, "Wait a minute! I thought Delphi didn't support variable parameters other than open arrays."

It doesn't. But there are certain functions built into the Delphi engine that can take variable numbers of parameters. Random is one of them, and off the top of my head, I can't name others. In any case, play around with this. For another reference, look up Random in the help file.

DevX Pro

 Submit a Tip Browse "Delphi And Pascal" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date