"Srand ((unsigned) time (NULL));" What the hell does that mean?

Source: Internet
Author: User
Tags rand random seed

1. Random numbers are calculated from random seeds according to a certain calculation method. So, as long as the calculation method is certain, random seed is certain, then the random number that produces will not change.

#include 
using namespace std; 

int main () 
{ 
unsigned int seed=5; 
Srand (seed); 
unsigned int r=rand (); 
cout<<r<<endl;

return 0;



2, as long as the user or third party does not set random seed, then by default, random seeds from the system clock (that is, the Timer/counter value)

#include 
using namespace std; 

int main () 
{ 
srand (unsigned) time (NULL)); 
unsigned int r=rand (); 
cout<<r<<endl;

return 0; 

Here the user and other programs do not set random seeds, the value of the system Timer/counter is used as a random seed, so, in the same platform environment, after compiling the build exe, each time it is run, the random number displayed will be pseudo random number, that is, the results of each run display will be different.


3 . Suggestion: If you want to generate a sequence of random numbers in a program, you need to set up a random seed at most before generating a random number. that is, simply call Srand ((unsigned) time (NULL) at the beginning of the main program; You can use Rand directly behind it. Do not place Srand ((unsigned) time (NULL)) in a for-wait loop;


From: Srand ((unsigned) time (NULL)); -lizhi200404520 's Column-Blog channel-csdn.net
http://blog.csdn.net/lizhi200404520/article/details/6707885


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.