我编写了一个内部有3个随机整数的数组.关键是我希望3个随机整数彼此不同(唯一的随机数).我的问题是,即使数字是唯一的,我仍然从他们那里得到一个"坏"的读数.我随机播放了随机数字(NULL),因此我在每个声明之间放了一个Sleep(x)函数来增加数字的变化.以下代码是我main()函数中的所有代码.出于测试目的,我没有在我的代码中包含break语句,所以我可以一遍又一遍地测试程序.
srand((unsigned)time(NULL));
while(true)
{
//Generate 3 numbers
int a = rand() % 7 + 1;
Sleep(1000);
int b = rand() % 8 + 1;
Sleep(1000);
int c = rand() % 9 + 1;
int array[3] = { a , b , c };
//Check the numbers to make sure none of them equal each other
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "bad" << endl;
system("pause");
system("cls");
}
else
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "good" << endl;
system("pause");
system("cls");
}
}
system("pause");
return 0;
Run Code Online (Sandbox Code Playgroud)
当前检查的问题是它检查由随机值表示的索引,而不是随机值本身,它们是前3个元素.
只需更换
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
Run Code Online (Sandbox Code Playgroud)
同
if( (array[0] == array[1]) || (array[0] == array[2]) || (array[1] == array[2]) )
Run Code Online (Sandbox Code Playgroud)
要不就
if(a == b || a == c || b == c)
Run Code Online (Sandbox Code Playgroud)