C++ 数组中的非重复元素 #包括 #包括 #包括 int main() { srand(time(NULL));//初始化随机种子 while(true){ const char arrayNum[4]={'1','3','7','9'}; int RandIndex=rand()%4;//生成一个介于0和3之间的随机数 cout
您可以创建一个bool数组,指示是否使用了索引C++ 数组中的非重复元素 #包括 #包括 #包括 int main() { srand(time(NULL));//初始化随机种子 while(true){ const char arrayNum[4]={'1','3','7','9'}; int RandIndex=rand()%4;//生成一个介于0和3之间的随机数 cout,c++,arrays,loops,random,C++,Arrays,Loops,Random,您可以创建一个bool数组,指示是否使用了索引 #include <iostream> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); //initialize the random seed while (true) { const char arrayNum[4] = { '1', '3', '7', '9' };
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL)); //initialize the random seed
while (true) {
const char arrayNum[4] = { '1', '3', '7', '9' };
int RandIndex = rand() % 4; //generates a random number between 0 and 3
cout << arrayNum[RandIndex];
}
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
srand(time(NULL));//初始化随机种子
const char arrayNum[4]={'1','3','7','9'};
bool-take[4]={false};
国际贸易指数;
对于(int i=0;i<4;i++){
做{
RandIndex=rand()%4;
}while(采取[随机指数]);
取[RandIndex]=真;
好吧…当你只从4中选择时,你不可能有一个无限循环不断打印不同的数字。你真正想要的是什么?请注意,消除重复会使你的序列更少随机,而不是更随机。让我们建议我有一个10次重复的for。我不想重复数字。我不清楚你是否想要避免连续的num避免重复,或者如果你想让整个序列中的每个数字都是唯一的。这种解决方案是可行的,但(平均而言)每个后续数字都需要越来越多的工作。而使用幻数则容易出错。@FrançoisAndrieux I同意这一点
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL)); //initialize the random seed
const char arrayNum[4] = { '1', '3', '7', '9' };
bool taken[4] = { false };
int RandIndex;
for(int i = 0; i < 4; i++){
do{
RandIndex = rand() % 4;
}while(taken[RandIndex]);
taken[RandIndex] = true;
cout << arrayNum[RandIndex];
}
}