天天看点

C++使用随机数

因为平时随机数用的比较少, 总是会忘记如何使用, 所以常常是要用的时候到网上去查找资料, 觉得挺麻烦, 干脆自己写一篇.

随机函数rand(), 包含在cstdlib头文件中. 有的博客文章给出的代码是没有这个的, 编译不通过, 误导别人.

基本的用法是这样的:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int num = rand();
    cout << rand() << endl;
}
           

然而只是这样的话, 生成的(伪)随机数不总是随机.

为什么说是不总是? 运行如下代码, 发现生成的一系列随机数始终相同

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    for(int i = ; i < ; ++i)
        cout << rand() << endl;
}
           

具体解释

解决这种问题的方法是使用srand函数

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand((unsigned)time(NULL));
    for(int i = ; i < ; ++i)
        cout << rand() << endl;
}
           

加个ctime头文件. srand函数的种子使用系统时间

另外, 可以使用宏定义自定义一个自由的区间的随机数

如:

//随机范围为[a,b]

#define random(a, b) rand()%(b-a+1) + a

同理其他