0
点赞
收藏
分享

微信扫一扫

c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数


随机数经常解题需要用到,生成大量的随机数,尤其是,有序的随机数,分享一下生成随机数的简单方法。

所用编译器vc6.0

①生成一个随机数

#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;
}

连续三次运行结果示例:

c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_随机数


c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_随机数


c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_随机数


生成随机数用ctime头文件,以上代码生成一个随机数但是每次运行都是一样的随机数由于 没有设置随机数种子

添加代码:

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;
}

三次连续运行结果示例:

c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_李阡殇_04


c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_李阡殇_05


c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_c++生成随机值_06

②生成 大量随机数据并且排序

以下利用了C++STL容器和迭代器,​​list双链表容器为例​​创建500个递增有序的随机数

#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;
}

运行截图:

c/c++利用time(),rand()生成随机数、生成单一随机数、生成大量有序随机数_rand()函数_07


举报

相关推荐

0 条评论