C++随机数的逻辑运算结果

C++ random numbers logical operator wierd outcome

本文关键字:结果 逻辑运算 随机数 C++      更新时间:2023-10-16

我正在尝试制作一个生成随机数字的程序,直到它找到一组预定义的数字(例如,如果我有一组我最喜欢的5个数字,我需要玩多少次才能让计算机随机找到相同的数字)。我写了一个简单的程序,但不理解结果,这似乎与我的预期略有无关,例如,结果不一定包含所有预定义的数字,有时确实包含(即使这样也不能阻止循环运行)。我认为问题出在逻辑运算符&'但我不确定。这是代码:

const int one = 1;
const int two = 2;
const int three = 3;

使用命名空间std;

int main()
{
    int first, second, third;
    int i = 0;
    time_t seconds;
    time(&seconds);
    srand ((unsigned int) seconds);
    do
    {

    first = rand() % 10 + 1;
    second = rand() % 10 + 1;
    third = rand() % 10 + 1;

    i++;
    cout << first<<","<<second<<","<<third<< endl;
    cout <<i<<endl;
    } while (first != one && second != two && third != three); 
    return 0;
 }

以下是可能的结果:

3,10,4
1 // itineration variable
7,10,4
2
4,4,6
3
3,5,6
4
7,1,8
5
5,4,2
6
2,5,7
7
2,4,7
8
8,4,9
9
7,4,4
10
8,6,5
11
3,2,7
12

我还注意到,如果我使用||运算符而不是&amp;循环将执行,直到找到与变量设置顺序相关的确切数字(此处:1,2,3)。然而,这更好,即使顺序不相同,只有数字,我该怎么做才能使循环停止?谢谢你的回答和帮助。

问题就在您的情况下:

} while (first != one && second != two && third != three);  

当他们都不平等时,你继续。但一旦其中至少有一个相等,您就停止/退出循环。

要解决此问题,请使用逻辑或(||)而不是逻辑和(&&)来链接测试:

} while (first != one || second != two || third != three);  

现在,只要他们中的任何一个不匹配,这种情况就会持续下去。

编辑-进行更高级的比较:

我将使用一个简单的宏使其更容易阅读:

#define isoneof(x,a,b,c) ((x) == (a) || (x) == (b) || (x) == (c))

请注意,您可以使用不同的方法。

} while(!isoneof(first, one, two, three) || !isoneof(second, one, two, three) || !isoneof(third, one, two, three))

您的逻辑条件有一个错误:它的意思是"当所有数字都不相等时"。要打破这个条件,一个对就足够相等了。

你需要构建一个不同的条件——要么在前面加上"不是"

!(first==one && second==two && third==three)

或者使用德摩根定律转换:

first!=one || second!=two || third!=three