C + + random number rand () and seed function Srand ()

Source: Internet
Author: User

In computer programming, a random number is often generated. But it's not that easy for a computer to produce a random number. The execution of a computer is carried out in code, so it is not possible to produce a number that really has a random meaning, like a draw or a dice. It is possible to generate a pseudo-random number with a certain algorithm, and C + + provides a function to be placed in the Cstdlib, called Rand (), with the prototype: int rand (void);

Obviously, this function does not accept any arguments, it does this by producing a random number between [0..rand_max]. Rand_max is also stored in Cstdlib, which is a macro constant:

   #define Rand_max ox7fff

Rand_max the largest is, the default is. However, it is not always possible to change the constants every time the range is changed. So this is generally used:

   Rand ()%max    // This expression generates a random number between [0..max-1]

This function does not produce random numbers in a vacuum, but requires a random number seed. This seed is provided by the Srand function, also stored in Cstdlib, with the prototype: void Srand (unsigned seed);. When you use Rand () but do not produce a seed in advance, the seed value is initialized by default to 1.

C + + random number rand () and seed function Srand ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.