路由器报价:怎么在C++中,随机产生几个数字,(不重复的)

来源:百度文库 编辑:中科新闻网 时间:2024/05/02 20:24:40

产生不重复的,需要在程序里保存一个已经生成的数字列表。每次随机生成的时候就在之中搜索有无同样的,如果有,就重新生成。
例:
假如要生成5个数字,则
include <time.h>
include <stdlib.h>

int numGen[5] = {0, 0, 0, 0, 0};
int index = 0;

bool isGenerated(int newNum) {
for(int i=0; i<index; i++) {
if(numGen[i] = newNum)
return true;
}

return false;
}

void main() {
srand((unsigned)time(NULL));

int newNum = rand();

for(index = 0; index < 5; index++) {
while(!isGenerated(newNum))
newNum = rand();

numGen[index] = newNum;
}
}

初识化随机数种子
#include<time.h>
srand((unsigned)time(0));