本文介绍了C ++随机数逻辑运算符wierd结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个程序产生随机数,直到找到一个预定义的数字(例如,如果我有一组我最喜欢的数字,我需要玩多少次,计算机随机找到相同数字)。我写了一个简单的程序,但不明白的结果,似乎与我的期望略有不相关,例如结果不一定包含所有的预定义的数字,有时它做(甚至不停止循环从运行)。我认为问题在于逻辑运算符'&',但我不知道。这里是代码:

I am trying to make a program generating random numbers until it finds a predefined set of numbers (eg. if I had a set of my 5 favourite numbers, how many times would I need to play for the computer to randomly find the same numbers). I have written a simple program but don't understand the outcome which seems to be slightly unrelated to what I expected, for example the outcome does not necessarily contain all of the predefined numbers sometimes it does (and even that doesn't stop the loop from running). I think that the problem lies in the logical operator '&&' but am not sure. Here is the code:

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

使用namespace std;

using namespace 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)。这是更好的,但我该怎么做循环停止,即使顺序不一样,只有数字?感谢您的答案和帮助。

I have also noticed that If I use the || operator instead of && the loop will execute until it finds the exact numbers respecting the order in which the variables were set (here: 1,2,3). This is better however what shall I do make the loop stop even if the order is not the same, only the numbers? Thanks for your answers and help.

推荐答案

问题在于您的情况:

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

您继续,而它们都不相等。但是一旦它们中的至少一个是相等的,你就停止/离开循环。

You continue while none of them is equal. But once at least one of them is equal, you stop/leave the loop.

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

To fix this, use logical or (||) rather than a logical and (&&) to link the tests:

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

现在只要任何一个不匹配,它就会继续。

Now it will continue as long as any of them doesn't match.

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

Edit - for a more advanced comparison:

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

I'll be using a simple macro to make it easier to read:

#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))

这篇关于C ++随机数逻辑运算符wierd结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:39