当前位置:网站首页>Generation of random numbers in C language [detailed explanation]

Generation of random numbers in C language [detailed explanation]

2022-06-09 02:47:00 embelfe_ segge

Catalog

One 、rand function and srand function

stay C The random function commonly used in language is rand function , It can be generated randomly 0 ~ rand_max The random number , The maximum value varies with the type of definition ,rand The function is contained in the header file stdlib.h in .

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=rand();
    printf("%d",a);
    return 0;
}

Running results …………………………………………
 Insert picture description here
You will find that the random number generated each time is the same , because rand The random number generated by a function is a pseudo-random number , It is calculated according to a number and a formula , This number we call “ seeds ”, But this seed is a fixed value after the system is started .

If you want to generate different random numbers every time , that , We're going to use srand function .

srand() The function prototype is :

void srand (usigned int seed);

rand() When generating random numbers , If you use

原网站

版权声明
本文为[embelfe_ segge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/159/202206081115019224.html