C语言随机数使用方法

随机数在编程中还是有所应用,最近从网上学习到这方面一点知识,想把它写下来。
一、使用随机数所需要的头文件和函数:
        头文件:cstdlib(C++ 的 standard libraray)    ctime
        函数:    rand()       srand(int seed);   time(NuLL);
二、随机数的的理解:
       随机数不是真的随机数,它是通过公式(有很多)计算出来的。它就像函数一样——srand(seed)中的seed好比自变量x,而rand()则是seed对应的因变量的值。
       换句话来说,如果seed值固定,那么产生的随机数也不变。 代码如下:
代码如下:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(1);
    for(int i = 1; i <= 5; i ++)
    {
        cout << rand() << " ";
    }
    return 0;
}

运行n次结果

41 18467 6334 26500 19169
--------------------------------
Process exited after 0.576 seconds with return value 0
请按任意键继续. . .

        如何产生更像“随机数”的随机数呢,这时候time(NULL)就排上用场。time(NULL)会返回自 Unix 纪元(January 1 1970 00:00:00 GMT)起的当前时间的秒数,因为时间在变,所以由rand()产生的随机数就不固定了。
代码如下:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(time(NULL));
    for(int i = 1; i <= 5; i ++)
    {
        cout << rand() << " ";
    }
    return 0;
}

运行第一次结果:

12114 22257 23578 61 16877
--------------------------------
Process exited after 0.5004 seconds with return value 0
请按任意键继续. . .

运行第二次结果:

12212 17030 2447 1064 31402
--------------------------------
Process exited after 0.4893 seconds with return value 0
请按任意键继续. . .
(可以看到,每次的结果不同)
三、随机数的使用公式
       rand() % 随机数的范围的长度 + 随机数范围的最小值
       举例:如果我要产生10 — 15 的随机数,公式为 rand() % (15 - 10 + 1) + 10。

原文地址:https://www.cnblogs.com/Serenaxy/p/10359027.html