multi comparison in one condition

Hi!
I was doing a simple exercise (slot machine with only 3 possible values ). It took me less then a minute to do it. Here's the code.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657`` ``````#include #include #include using namespace std; int random(); int number1; int number2; int number3; int main() { srand(time(NULL)); cout<<"Welcome to the slot machine game! \n"; cout<<"List of combinations \n"; cout<<"1 1 1=1\$ \n"; cout<<"2 2 2=2\$ \n"; cout<<"3 3 3=3\$ \n"; cout<<"let's begin \n"; cout<<"\n"; do { number1=random(); number2=random(); number3=random(); cout<>retry; if (retry=='n') { break; } } while (true); return 0; } int random() { return rand()%3+1; }``````

After testing this program and seing it worked, I tried to simplify the if condition:
 ``1234`` `````` if (number1==number2==number3==1) { cout<<"You won 1\$ \n"; }``````

I tested it and saw that it's not precise, and even non winning combinations (like 2 2 1 or 3 3 1) would make me win 1\$. Can someone explain me why it doesn't work?
Thanks!

PS: I know that my "try again" isn't perfect because if someone enters another letter than 'y' or 'n' it would still repeat. I just didn't want to lose my time on this.
Only works with
 ``1234`` `````` if (number1==1&&number2==1&&number3==1) { cout<<"You won 1\$ \n"; }``````

becuase comparaison between two statments return a boolean value if if statments get a true value excutes it contents if not skeep to the next

you here want to compare 4 statements! at once wich I think it is invalid
Last edited on
closed account (3qX21hU5)
A easy way to shorten it would be just to test the variables against eachother. If number1 is equal to number2 and number2 is equal to number3 that means there was a winner. Then you can just print whatever number is in them variables to tell the user how much they have won.

For example.

 ``1234`` ``````if (number1 == number2 && number2 == number3) { cout << "You won \$" << number1 << "!" << endl; }``````
Last edited on
ok! Thanks to you two for your fast and good replies!
 Can someone explain me why it doesn't work?

It doesn't work because of the order of evaluations.

 `` `` ``(number1==number2==number3==1)``

gets evaluated in several steps:

First, `number1==number2` are compared. This results in a `true` or `false` boolean result. This result is then compared to number3, again resulting in a `bool` result. This bool result is then compared to the number 1.

Equivalent code:
 ``1234`` ``````temp_bool_result1 = (number1==number2) temp_bool_result2 = (temp_bool_result1 == number2) temp_bool_result3 = (temp_bool_result2 == number3) bool_result = (temp_bool_result3 == 1)``````

ok now I understand perfectly! Thanks AbstractionAnon!
Topic archived. No new replies allowed.