我的意图是生成从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;
}
只需生成数字1到9,然后使用std::random_shuffle
随机洗牌。
int nums[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::random_shuffle(nums, nums + 9);
这将使nums
以随机顺序具有从1到9的数字,没有重复。
您的重复检查循环有一个缺陷:check
设置为检查最后一对值的结果,而不是检查前面所有值对的结果。
您需要在内部循环之前设置check = true
,然后继续验证从零到i-1
的所有项目。如果检查在任何时候变为false
,则停止循环:
check = true;
for (j = 0 ; (check) && (j < i) ; j++) {
check = (num[i] != num[j]);
}
此外,您需要修复randrange
,因为您当前的实现返回范围为2..11
:的值
int randrange(int low,int high)
{
return rand()%(high-low+1)+low;
}
您的程序有许多缺陷,其中之一是randrange
函数返回的随机数范围。不是1比9!
然而,您的程序(程序挂起)的直接原因是,您将check
设置为false
,然后执行一个不执行任何操作的循环(因为第一次i
是0
,而从未执行带有j
的内部循环),因此check
将始终是false
。
检查其他答案以获得解决方案。
您的程序可能正在循环。由于奇怪的缩进,读取代码有点困难,但在for循环中似乎有一个逻辑缺陷:
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);
您可能需要删除第二行check=false;
来执行我认为您正在尝试的操作。
好吧,你可能已经通过dasbinkenlight的答案解决了这个问题
除了Peter的答案,你还可以使用std::map
来实现唯一的随机数:
std::map<int,int> m;
srand (time (NULL));
for(i=0;i<9;i++){
do{
j=randrange(1,9);
}while(m.find(j)!=m.end());
m[j]; //insert into map, no need for value.
num[i]=j;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
void rnd(vector<int> &v, const int n){
for (size_t i=0;i<=n;++i){
v.push_back(i);
}
random_shuffle(v.begin(), v.end());
}
void PrintVector(const vector<int> &x){
for (size_t i=0;i<x.size(); ++i){
cout<<x[i]<<'t';
}
}
int main(){
vector<int> a;
rnd(a,10);
PrintVector(a);
}
这段代码对我来说很好,可以生成一个从1到9的随机数数组,而不会重复
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(){
srand(time(0));
int arr[10];
for(int i=0; i<9; i++){
arr[i] = i+1;
cout << arr[i] << " ";
}
int j=0;
int temp=0;
cout << "nnn-------------------------nnn";
for(int i=0; i<9; i++){
j = (rand()%8)+1;
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
for(int i=0; i<9; i++){
cout << arr[i] << " ";
}
}