//////////////////////////////////////////////////////////////////
// name:一个取n个不同的随机数的算法
// author:zhaoyongpeng
// date:2006.5.26
///////////////////////////////////////////////////////////////////
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a[100]={0};
int i=0,length=0,value = 0;
cout<<" 请输入一个上限整数数值: ";
cin>>value;
cout<<"请输入你想得到的互不相同的整数值(应该小于"<<value<<"):";
cin>>length;
bool flag=true;
int temp=0;
/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );
for(i=0;i<length;i++)
{
temp=rand()%value;
if(i!=0)
{
flag=true;
while(flag)
{
flag=false;
for(int j=0;j<i;j++)
{
if(a[j]== temp)
{
flag=true;
temp=rand()%value;
break;
}
}
}
a[i]=temp;
}
else
{
a[0]=temp;
}
}
for(i=0;i<length;i++)
{
cout<<a[i]<<"/t";
}
cout<<endl;
return 0;
}
本文介绍了一个C++实现的算法,用于生成指定数量的不重复随机整数。用户可以设定随机数的最大值及所需的随机数数量。该算法通过循环与条件判断确保生成的随机数集合中没有重复元素。

1万+

被折叠的 条评论
为什么被折叠?



