How to get a random number in pascal?

59,662

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

Share:
59,662

Related videos on Youtube

gregory boero.teyssier
Author by

gregory boero.teyssier

https://ali.actor

Updated on July 09, 2022

Comments

  • gregory boero.teyssier
    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
      wallyk about 13 years
      Wow! Someone still uses Pascal?! I haven't used that since the early 1980s.
  • gregory boero.teyssier
    gregory boero.teyssier about 13 years
    If I wanted from between 100-300, then I'd do random(200)+100?
  • Ralph
    Ralph about 13 years
    Yes absolutely correct - please note I'm not too familiar with pascal so you may have to clean up the syntax
  • CodesInChaos
    CodesInChaos over 11 years
    Note that in most implementations, the random returns very low quality random numbers.
  • Thomas
    Thomas almost 11 years
    In that case you also need min - 1 else you'll never get min. 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 of max, you should do random(max - min). For a general purpose solution you also want to check that min <= max else things will break.
  • Benjamin Gruenbaum
    Benjamin Gruenbaum almost 9 years
    This adds nothing over the answer from 4 years ago.

Related