c++学习:产生随机数的方法

  • Post author:
  • Post category:其他




方法一:使用”time(NULL)”函数

time()函数的用途是返回一个值,即格林尼治时间1970年1月1日到当前时刻的时长,时长单位是秒。

需要包含头文件

<ctime>

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
int rand_number()
{
    return time(NULL);
}
int main()
{
    cout<<rand_number();
    cout<<" ";
    cout<<rand_number();
    return 0;
}

因为time(NULL)每秒钟返回值递增一次。而程序的运行时间小于1s,故而两次值是相等的。



方法二:使用

rand()



srand()

函数

rand函数是用来产生随机数的函数,(需要头文件

cstdlib

)但实际上产生的是伪随机数,并不是真正意义上的随机数,它是从一个随机数的序列种按照顺序返回其中的一个数。

随机数需要根据种子来产生,但是一开机种子就定下了(默认1),如果种子不变,那么产生的随机数序列也是相同的;种子变化,产生的随机数序列随之变化,所以只调用rand每次都是一样的值。

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>//rand()的头文件
using namespace std;
int main()
{
    int a;
    a=rand();
    cout<<a;
}

此例无论多少次打开程序都是一样的值,41;

常用的是结合

srand()

函数来种子,如使用“time(NULL)”作为种子。由第一种方法知道,这个数一秒钟变化一次,于是产生的随机数序列也是一秒钟变化一次。

#include <iostream>
#include <string>
#include <ctime>
#include <conio.h>//kbhit()函数
using namespace std;

int rand_number()
{
    srand(time(NULL));
    return rand();
}
int main()
{
    int i;
    while(true)
    {
        i=rand_number();
        cout<<i<<endl;
        if(kbhit())break;
    }
    system("pause");
    return 0;
}

但是这种方式数据更新是以秒为单位的,一秒内调用rand_number()函数种下的种子是相同的,故而随机数的序列是相同的,故而一秒内产生的随机数是相同的。

要想产生不同的随机数,应将

srand(time(NULL));



int i;

的后面,这样虽只种下了一次种子,确定了一个随机数列,但每次调用产生的随机数是不相同的。

#include <iostream>
#include <string>
#include <ctime>
#include <conio.h>//kbhit()函数
using namespace std;
int main()
{
    int i;
    srand(time(NULL));//如果将其注释掉,每次运行代码产生的随机序列均相同
    while(true)
    {
        i=rand();
        cout<<i<<endl;
        if(kbhit())break;//判断是否有按键动作,如果有就返回true
    }
    system("pause");
    return 0;
}



版权声明:本文为jinniulema原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。