Problem-solving often need to use a random number, generate a lot of random numbers, in particular, ordered random number, a simple method to share about generating random numbers.
The compiler used vc6.0
① generates a random number
#include<ctime>
#include<iostream>
using namespace std;
#define random() (rand()%x) //定义随机值的范围 0~x
int main(int argc, char* argv[])
{
cout<<rand()%100<<endl; //输出一个100以内的随机值
return 0;
}
The results of three continuous operation Example:
generating a random number with ctime header, the above code generates a random number for each run are the same, but the random number since there is noSet random seed;
Add code:
srand((unsigned)time(NULL));
#include<ctime>
#include<iostream>
using namespace std;
#define random() (rand()%x) //定义随机值的范围 0~x
int main(int argc, char* argv[])
{
srand((unsigned)time(NULL));//设置随机数种子
cout<<rand()%100<<" "<<endl; //输出一个100以内的随机值
return 0;
}
Three consecutive run Example result:
② generate large random data and the ordering
The following use of the C ++ STL containers and iterators , List doubly linked list container, for example to create 500 increments ordered random number
#include<ctime>
#include<iostream>
#include<iomanip>
#include<list> //list双链表容器头文件
using namespace std;
#define random() (rand()%x) //定义随机值的范围 0~x
int main(int argc, char* argv[])
{
srand((unsigned)time(NULL));//设置随机数种子
list<int> a; //定义一个int型的动态数组a
for(int i=0;i<500;i++)
{
a.push_back(rand()%10000); //尾端插入链表
a.sort(); //升序排序
a.unique();//去除重复元素
}
list<int>::iterator it; //构建一个list容器的迭代器it
cout<<"-------------------------------五百个递增有序随机数---------------"<<endl;
for( it = a.begin();it!=a.end();it++)
{
cout<<setw(4)<<*it<<" "; //取list容器中的值输出
}
cout<<endl;
return 0;
}
Run shot: