How to get a random number in pascal?
Solution 1
Just get a random number with the correct range (ie 100 to 200 would be range 100) then add the starting value to it
So: random(100) + 100
for your example
Solution 2
As already pointed out, you should use
myrandomnumber := random(span) + basenumber;
However, to get better quality random numbers, you should call
randomize();
once, on start of your application, to initialize the random number generator.
Solution 3
Couldn't you just declare a starting variable and an end variable and pass random those? e.g.
var
varMyRandomNumber, x, y := extended;
begin
x := 100;
y := 200;
varMyRandomNumber := random(x,y);
ShowMessage(IntToStr(varMyRandomNumber));
end;
?
There's a good example here of using a for loop to set starting and end values : http://www.freepascal.org/docs-html/rtl/system/random.html
Related videos on Youtube
Comments
-
gregory boero.teyssier almost 2 years
I want to get a random number in pascal from between a range. Basically something like this:
r = random(100,200);
The above code would then have a random number between 100 and 200.
Any ideas?
The built in pascal function only lets you get a number from between 0-your range, while i need to specify the minimum number to return
-
wallyk about 13 yearsWow! Someone still uses Pascal?! I haven't used that since the early 1980s.
-
-
gregory boero.teyssier about 13 yearsIf I wanted from between 100-300, then I'd do
random(200)+100
? -
Ralph about 13 yearsYes absolutely correct - please note I'm not too familiar with pascal so you may have to clean up the syntax
-
CodesInChaos over 11 yearsNote that in most implementations, the
random
returns very low quality random numbers. -
Thomas almost 11 yearsIn that case you also need
min - 1
else you'll never getmin
. But in general in programming when we say "between X and Y" we mean "between X inclusive and Y exclusive" - this simplifies a bunch of stuff so the formula is just min + random(span), no need for a +1. Also your bound of 10000 is arbitrary and won't work for all values ofmax
, you should dorandom(max - min)
. For a general purpose solution you also want to check thatmin <= max
else things will break. -
Benjamin Gruenbaum almost 9 yearsThis adds nothing over the answer from 4 years ago.