李旼赫日历女孩:用c++编程,如何让1,2,3,4,5随机排列

来源:百度文库 编辑:高校问答 时间:2024/05/10 19:24:59

用一个tag[5]数组来表示1-5是否已产生,然后循环生成1-5之间的随机数,每生成一个数i,则通过检查tag[i-1]来判断i是否已产生过,若产生过,则继续循环,若未产生过,则输出i。产生5个数后,循环结束。

#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int a[5] = {0,0,0,0,0};
srand((unsigned)time(NULL));
for(int i = 0; i < 5; i++)
{
int k = rand() % 5 + 1;
while(a[k-1] == 1)
{
k = rand() % 5 + 1;
}
cout<<k<<endl;
a[k-1] = 1;
}
}

楼上的回答的很好啦,顶