//自己写逻辑的方法
#include "stdafx.h"
#include <ctime>
#include <iostream>
using namespace std;
#define MAX_NUM 10
#define RAN_NUM 5
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int list_num[MAX_NUM];
int random_num[RAN_NUM];
int random;
bool flag;
for (int i=0;i<MAX_NUM;++i)
{
list_num[i]=i;
}
for (int i=0;i<RAN_NUM;++i)
{
flag=true;
random=rand()%MAX_NUM;
for (int j=0;j<i;++j)
{
if(random_num[j]==random)
{
flag=false;
break;
}
}
if (flag)
{
random_num[i]=random;
}
else
{
--i;
}
}
for (int i=0;i<RAN_NUM;++i)
{
cout<<random_num[i]<<" ";
}
getchar();
return 0;
}
//STL的实现方法
for (int i=0;i<RAN_NUM;++i)
{
cout<<random_num[i]<<" ";
}
vector<int> Vec;
for(int i=0;i<MAX_NUM;++i)
{
Vec.push_back(i);
}
for (int i=0;i<RAN_NUM;++i)
{
int random_num=rand()%(int)Vec.size();
cout<<Vec.at(random_num);
Vec.erase(Vec.begin()+random_num);
}
//方法一,老工程师说++ --一起出现特别容易崩溃吧,让最好一个循环写出来,同学们还有什么好方法吗?
<pre name="code" class="cpp">int exists(const int *a,int size,int num)
{
for (int i=0;i<size;++i)
{
if (a[i]==num)
{
return 1;
}
}
return 0;
}
srand((unsigned)time(NULL));
int anum[MAX_RAN];
int index=0;
while (index<MAX_RAN)
{
int num=rand()%10;
if (!exists(anum,index,num))
{
anum[index]=num;
index++;
}
}
for (int i=0;i<MAX_RAN;++i)
{
cout<<anum[i]<<" ";
}