1

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;

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;
 }

and here is out of the possible outcomes:

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

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.

4

2 に答える 2

4

問題はあなたの状態でここにあります:

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

それらのどれも等しくない間、あなたは続けます。しかし、それらの少なくとも1つが等しくなると、ループを停止/終了します。

これを修正するには、論理積(||)ではなく論理積または()を使用&&してテストをリンクします。

} 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))
于 2012-08-28T10:16:55.403 に答える
1

あなたはあなたの論理的条件に誤りがあります:それは「すべての数が等しくない間」を意味します。この状態を打破するには、1つのペアが等しくなるだけで十分です。

別の条件を作成する必要がありました-その前に「not」を置くか

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

または、ド・モルガンの法則を使用して変換します。

first!=one || second!=two || third!=three
于 2012-08-28T10:17:15.043 に答える