Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

6.5 Random number

1 min read
Image result for rand() logo
C (and by extension C++) comes with a built-in pseudo-random number generator. It is implemented as two separate functions that live in the cstdlib header:
srand() sets the initial seed value. srand() should only be called once.
rand() generates the next random number in the sequence (starting from the seed set by srand()).

Here’s a sample program using these functions:
int main()
{
int count;
srand(5323);
// set initial seed value to 5323

// Print 10 random numbers
for (i=0; i < 10; i++)
{
cout << rand() << "\t";
}
}

The output of this program will be any 10 numbers.

The range of rand()

rand() generates pseudo-random integers between 0 and RAND_MAX, a constant in stdlib that is typically set to 32767.

Generally, we do not want random numbers between 0 and RAND_MAX — we want numbers between two other values, which we’ll call Low and High.
For example, if we’re trying to simulate the user rolling a dice, we want random numbers between 1 and 6.

It turns out it’s quite easy to take the result of rand() can convert it into whatever range we want:
// Generate a random number between Low and High (inclusive)
unsigned int GetRandomNumber(int Low, int High)
{
return (rand() % (High - Low + 1)) + Low;
}

                      7.1 Function Basics          NEXT >>

You may like these posts

  • In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin. cin is an instance of iostream class For f…
  • if statement An if statement contains a Boolean expression and block of statements enclosed within braces. Structure of if statement if (boolean expression ) /* if expression …
  • On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. cout is an instance of iostream class …
  • The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object…
  • C++ allows us to create own own data types. enumerated type is the simplest method for doing so. An enumerated type is a data type where every possible value is defined as a s…
  • The predefined object cerr is an instance of iostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the objec…

Post a Comment