Home > Backend Development > C#.Net Tutorial > What does the srand(time(0)) function mean?

What does the srand(time(0)) function mean?

藏色散人
Release: 2019-06-06 10:57:06
Original
30123 people have browsed it

The standard library defines a set of random number engine classes and adapters that use different mathematical methods to generate pseudo-random numbers. The standard library also defines a set of distribution templates to generate random numbers according to different probabilities. The names of engines and distribution types correspond to their mathematical properties.

What does the srand(time(0)) function mean?

But today we will touch on a little bit of the most basic knowledge.

The computer has no way to generate real random numbers. It uses algorithm simulation, so you only call rand, and the things that come out are the same every time. After setting a seed, different numbers can be generated depending on the seed. And how to ensure that the seeds are different? The simplest way is of course to use time that is always moving forward.

srand(time(0)) ;//先设置种子
rand();//然后产生随机数
Copy after login

Srand is the number of random seeds planted. The seeds you plant are different every time, and the random numbers obtained by using Rand are different. In order to plant a different seed every time, Time(0) is used. Time(0) is to get the current time value (because the time is different every moment).

srand(time(0)) ;It is to give this algorithm a startup seed, which is the random seed number of the algorithm. Only after this number can the random number be generated, use 1970.1.1 The number of seconds since which the random number seed was initialized.

Reference case

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void main ( void )
{
    int i;
    
    srand(time(0));
    
    /* 输出 10 个随机数. */
    for (i = 0; i < 10; i++)
        printf( "%6d/n", rand());
}
Copy after login

Output result:

   22614
   15772
   30620
   24913
    7556
   31659
   27876
   27229
   25083
   16564
Copy after login

Related recommendations: "C Video Tutorial"

The above is the detailed content of What does the srand(time(0)) function mean?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template