利用srand()和rand()生成随机密码

先用srand函数设置一个种子,一般为当前时间,然后使用rand函数产生随机数,如产生a~b的随机数使用表达式rand()%(b-a+1)+a。

注意:srand函数在头文件#include 中。

#include 
#include 
#include 
int main()
{
    int a[10]/*用于保存10个产生的随机数*/, i;
    srand((unsigned int)time(NULL));//设置当前时间为种子
    for (i = 0; i < 10; ++i){
        a[i] = rand()%100+1;//产生1~100的随机数
    }
    //打印生成的随机数
    for (i = 0; i < 10; ++i){
        printf ("%d ", a[i]);
    }
    printf ("\n");
    return 0;
}

执行结果: 

利用srand()和rand()生成随机密码_第1张图片 

 若将srand()函数屏蔽,或者将srand()函数参数(也就是种子)设置为定值。例如 : srand(1),则执行结果如下:

利用srand()和rand()生成随机密码_第2张图片

int rand(void);

void srand(unsigned int seed);

1、rand()函数不需要任何参数,直接返回一个随机数,注意,这个随机数是有范围的,在0~RAND_MAX之间,RAND_MAX一般最小取值为32767,其具体值在头文件stdlib.h中进行定义

2、srand需要一个无符号整形数作为参数(种子),如果作为种子的无符号数相同,那么获取的随机数也就相同,注意:srand()必须配合rand()使用才能有效果 

下面是用法:

 

#include 
#include 
#include 
using namespace std;
 
int main()
{
    int i;
 
    cout << "测试rand()函数" << endl;
    cout << "随机数最大值RAND_MAX为:" << RAND_MAX << endl;
    for (i = 0; i < 3;i++)
    {
        cout << "num = " << rand() << endl;
    }
 
    cout << "测试srand()函数" << endl;
    cout << "使用不同的种子生成随机数" << endl;
    for (i = 0; i < 3;i++)
    {
        srand(i);
        cout << "num = " << rand() << endl;
    }
 
    cout << "使用相同的种子生成随机数" << endl;
    for (i = 0; i < 3;i++)
    {
        srand(2);
        cout << "num = " << rand() << endl;
    }
}

 执行结果:

利用srand()和rand()生成随机密码_第3张图片

 

特定随机数的生成

为了使rand()函数生成的随机数在一定的范围内,可以使用如下表达式

1

a + rand() % n

使用上述表达式生成的随机数的范围在a ~ (a + n)之间,其中a为生成的随机数的最小值,a + n - 1为最大值。例子如下

#include 
#include 
#include 
using namespace std;

int main()
{

    cout << "生成特定范围内的随机数:" << endl;
    cout << "生成5 到 15 之间的随机数" << endl;
    for (int i = 0; i < 5;i++)
    {
        cout << "num = " << 5 + rand() % 10 << endl; //可生成5,6,7,...,14,不包含15

    }
}

 

结果如下

利用srand()和rand()生成随机密码_第4张图片

使用系统时间作为种子生成随机数

为了让随机数更像随机数,降低人为因数的干扰,可以使用系统当前时间作为种子产生随机数

#include 
#include      //时间函数time()的头文件
#include   //暂停函数Sleep()的头文件
using namespace std;
int main()
{
    cout << "使用系统时间作为种子生成随机数:" << endl;
    for (int i = 0; i < 5;i++)
    {
        Sleep(1000);    //暂停一秒,避免因程序执行过快,5次循环中系统时间未发生变化,导致产生的随机数也相同

        srand((unsigned)time(NULL));

        cout << "num = " << rand() << endl;
    }
    return 0;
}

 

 

 

你可能感兴趣的:(嵌入式开发)