Don
Don

Reputation: 13

(C++) Random numbers are equal, but program says they aren't

I am a beginner, and I created a slot machine simulator. The wheel is spun and x, y, and z are set to random numbers. I have an if statement that checks to see if x == y == z. When the program runs, and the numbers are in fact equal, it runs my code that says they are not equal. Why does this happen?

For example, the cout statement will say 2 -- 2 -- 2, then it goes to my if statement for when they are not equal, and I get the "you lose" code.

I should add, this does not happen every time. Sometimes it properly executes the if statement for when they are equal. It is very odd.

    srand(time(0));

    int x = (rand() % 2) + 1;
    int y = (rand() % 2) + 1;
    int z = (rand() % 2) + 1;

    std::cout << "The spin results are... " << x << " -- " << y << " -- " << z << std::endl << std::endl;

    if( x == y == z)
    {
    std::cout << "You win!\n\n";
    playerCoins = playerCoins + (coinsBet * 2);
    }
    else 
    {   
        std::cout << "You lose!\n\n";
    }

Upvotes: 1

Views: 149

Answers (4)

marc_s
marc_s

Reputation: 455

You should use Logical operators.

the expression, x == y == z is wrong.
it should be done this way.

if((x == y) && (y == z)) {    //or... if ((x == y) == z)
//your code goes here...
}

More information about logic operators, Here.

Upvotes: 0

Andreas DM
Andreas DM

Reputation: 11018

The expression if (x == y == z) is evaluated to false.

Pretend x, y, and z all hold the value 2:

Because (x == y) is then true / 1. And z is holding the value 2, the if statement will check:

if ((x == y) == z)
//     1   ==   2

Which becomes:

if (1 == 2) {} // false

You can fix that by doing this:

if ((x == y) && (y == z)) { /* ... */ }

Upvotes: 2

A B
A B

Reputation: 487

x == y may result in 0 or 1, depending on their true or false value. Then 0 or 1 is compared with z, this why the given result is false.

The correct method is to check if x equals z and y equals z, which of course also means that x equal y. (x == z) && (y == z)

Upvotes: 4

fredoverflow
fredoverflow

Reputation: 263220

x == y == z does not do what you think it does. Use x == y && y == z instead.

Upvotes: 4

Related Questions