使用步骤:
- 包含库 cstdlib
#include <cstdlib>
- 使用时间当做随机数种子
srand(time(NULL));
- 调用rand来返回随机数
std::cout<<RAND_MAX<<std::endl;
std::cout<<rand()<<std::endl;
- rand只能生成 范围通常是 0 到 RAND_MAX 之间。
代码示例
头文件:
#ifndef RANDTEST_H
#define RANDTEST_Hclass RandTest
{
public:RandTest();void Lean();int rands(int min,int max);
};#endif // RANDTEST_H
代码:
#include "randtest.h"
#include <iostream>
#include <cstdlib>using namespace std;RandTest::RandTest()
{srand(time(NULL));
}void RandTest::Lean()
{//随机数最大值 32767std::cout<<RAND_MAX<<std::endl;for(int i=0;i<10;i++){std::cout<<rand()<<std::endl;}
}//由于 RAND_MAX 的问题,所以max最好是小于等于32767
int RandTest::rands(int min,int max)
{return rand() % (max - min + 1)+min;
}
main.cpp
#include "randtest.h"#include <iostream>using namespace std;int main()
{string str="随机数学习";std::cout<<str<<std::endl;auto a = new RandTest();//获取随机数a->Lean();std::cout<<a->rands(100,1000)<<endl;return 0;
}