C++ C++;不重复地生成随机数。输出屏幕上只有一个闪烁的光标
我的目的是不重复地生成从1到9的随机数C++ C++;不重复地生成随机数。输出屏幕上只有一个闪烁的光标,c++,random,C++,Random,我的目的是不重复地生成从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
#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;
}
#包括
#包括
#包括
使用名称空间std;
int randrange(int low,int high)/*在给定范围内生成一个随机数*/
{
返回rand()%(低+高)+低+1;
}
int main()
{
int num[9]={0},i,j;
布尔检查;
对于(i=0;i重复检查循环有一个缺陷:检查
设置为检查最后一对值的结果,而不是检查前面所有对的结果
您需要在内部循环之前设置check=true
,然后继续验证从零到i-1
的所有项目。如果检查在任何点变为false
,请停止循环:
check = true;
for (j = 0 ; (check) && (j < i) ; j++) {
check = (num[i] != num[j]);
}
只需生成数字1到9,然后使用
这将使nums
以随机顺序保留从1到9的数字,并且不会重复。您的程序有许多缺陷,其中之一是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;
做
{
num[i]=随机范围(1,9);
对于(j=0;j好的,你可能已经通过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;
}
std::map m;
srand(时间(空));
对于(i=0;i#包括
#包括
#包括
#包括
使用名称空间std;
无效rnd(矢量和v,常数整数n){
对于(size_t i=0;i)虽然这是一个更好的算法,但它不能回答OP的问题:问题是什么,程序为什么挂起。堆栈溢出时不鼓励使用纯代码答案,因为它们不能解释它是如何解决问题的。此外,当回答一个有可接受答案的老问题时(寻找绿色)✓) 以及其他答案,确保您的答案添加了新的内容或与之相关的其他有用内容。-请编辑您的答案,解释此代码的作用以及它如何改进其他答案。
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);
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);
}