C++随机数的逻辑运算结果
C++ random numbers logical operator wierd outcome
我正在尝试制作一个生成随机数字的程序,直到它找到一组预定义的数字(例如,如果我有一组我最喜欢的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
我还注意到,如果我使用||运算符而不是&;循环将执行,直到找到与变量设置顺序相关的确切数字(此处: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
相关文章:
- 算术运算的结果类似于:C浮点变量中的1/3
- 数组上的相同逻辑会产生不同的结果
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 逻辑错误,我将获得意外结果
- 提升有关逻辑运算的摩擦问题
- 在生成子序列时使用按位运算的逻辑是什么?
- 相同的算术运算在 C++ 和 Python 中给出不同的结果
- (MPIC )MPI_SCATTER产生错误的结果(逻辑错误)
- 如果两者都会给出相同的结果,我应该更喜欢加法或逻辑 OR 运算符吗?
- C++随机数的逻辑运算结果
- 浮点运算结果的重现性
- 如何正确返回矩阵乘法运算的结果
- 确定两个矢量类型或一个矢量类型与标量类型之间的二进制运算结果的正确大小类型
- 赋值逻辑操作的结果
- 谁在Java或C++源代码中执行算术和逻辑运算
- 这个逻辑运算工作有什么问题?
- cout 中的逻辑运算
- 逻辑运算:我想使逻辑运算容易
- 这就是avx浮点位逻辑运算的原因
- C/ c++中对大文件二进制数据的逻辑运算