3 c++ random numbers non-repetitive
我的目的是从1到9生成随机数而不重复
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int randrange(int low,int high) /* generates a random number within given range*/
{
return rand()%(low+high)+low+1;
}
int main()
{
int num[9]={0},i,j;
bool check;
for(i=0;i<9;i++)
{
check=false;
do
{
num[i]=randrange(1,9);
for(j=0;j<i;j++)
{
if( num[i]==num[j]) // checks whether number already exists in the array
check=false;
else
check=true;
}
} while(check==false);
}
// the program is working fine without the repetition check
// this section prints out the array elements
for(i=0;i<9;i++)
{
cout<<num[i]<<" ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
只需生成数字1到9,然后使用随机播放它们std::random_shuffle.
int nums[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::random_shuffle(nums, nums + 9);
Run Code Online (Sandbox Code Playgroud)
这将以nums随机顺序从1到9的数字离开,没有重复.
您的重复检查循环有一个缺陷:check设置为检查最后一对值的结果,而不是检查所有前面的对的结果.
您需要check = true在内部循环之前设置,然后继续验证从零到的所有项目i-1.如果检查false在任何时候,请停止循环:
check = true;
for (j = 0 ; (check) && (j < i) ; j++) {
check = (num[i] != num[j]);
}
Run Code Online (Sandbox Code Playgroud)
此外,您需要修复randrange,因为您当前的实现返回范围内的值2..11:
int randrange(int low,int high)
{
return rand()%(high-low+1)+low;
}
Run Code Online (Sandbox Code Playgroud)