Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to Generate random numbers Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
27-Dec-02
Category
Algorithm
Language
Delphi 2.x
Views
86
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			Author: Lou Adler

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...

Answer:

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:
1   
2   function GetRandomInt(UpperRange: Integer): Integer;
3   begin
4     Randomize;
5     Result := Random(UpperRange);
6   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.

			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC