Borthamonth Borthamonth - 21 days ago 6
C++ Question

"and" and "or" operators

I'm new to coding and currently following the jumping into c++ book. I was making a slot machine that loops until all three strings have the same value. I'm confused as to why in this code the "or" operator is giving the desired result rather than the "and" operator. I wanted the program to check for both and that both need to be true, but that only works if I use the "or" operator. Thanks :)

using namespace std;

int randomNum(int low, int high) {
return rand() % (high - low) + low;
}


int main()
{
srand(time(NULL));
string slot[3] = { "Apple", "Banana", "Pumpkin" };
string slotA;
string slotB;
string slotC;
int guess = 0;

do {
slotA = slot[randomNum(0, 3)];
slotB = slot[randomNum(0, 3)];
slotC = slot[randomNum(0, 3)];
cout << slotA << "\t" << slotB << "\t" << slotC << "\n";
guess++;
} while (slotB != slotC || slotB != slotA);

cout << "You won the jackpot in " << guess << " guesses!";

cin.ignore();
cin.get();
return 0;
}

Answer

Your stop condition should be:

while (!(slotB == slotC && slotB == slotA));

However, in Bool-Algebra !(slotB == slotC && slotB == slotA) is equal to slotB != slotC || slotB != slotA

This rule is called De Morgan Law