rand () and srand () usage

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/yinuoheqian123/article/details/82788196

rand () generates a pseudo-random number is required srand () to set up a seed, the system time usually

Example:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand (Time (NULL)); // time using the system generates a random number
for (int i = 0; i <10; I ++)
{
the printf ( "% D \ T", RAND ());
}

}

You will be found to produce 10 different random number each time it runs.

If you want to limit the scope of the random number generated, you can use the following code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand (Time (NULL));
for (int I = 0; I <10; I ++)
{
the printf ( "% d \ t", rand ()% 20 + 100); // in the range of 100 to 120,20 represents the length, representing the starting position 100
}

}

To generate a random number in the range 0 to 1, using the following code:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
printf("%2f\t", (rand()%100)/100.0);//注意100.0的”.0”不能漏掉
}

}

Reference: https://blog.csdn.net/weixin_40790467/article/details/79715270

Guess you like

Origin blog.csdn.net/yinuoheqian123/article/details/82788196