C + + random number produces same solution

Source: Internet
Author: User
Tags rand

Keep in mind srand () do not call two times or more than two times.

void Main ()
{
for (int i=0;i<10;i++)
{
Srand ((unsigned) time (NULL));
Cout<<rand () <<endl;
}
}

When this is called, the Srand ((unsigned) time (NULL) is invoked because of the high speed relationship of the CPU; The number of seeds generated. Causes rand () to produce random numbers as well.

To

void Main ()
{srand (unsigned) time (NULL));
for (int i=0;i<10;i++)
{
Cout<<rand () <<endl;
}
}

Sometimes these errors are hidden and a check method is made in the constructor. Call the Init method in the check method, and then generate a random number in the Init method. Note If Srand ((unsigned) time (NULL)); is written in a check () or init () method, make sure that the method is only invoked once at construction time. It is best to put the line code Srand ((unsigned) time (NULL)), and write to the constructor to initialize the seed.

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.