if (guess = randomNumber)
if (guess == randomNumber)
if (c = 'h')
at line 67. The reason is because using = you assign 'h' to the variable c instead of asking if c is equal (==) 'h' if('h')
which, being a value other than 0 equates to true, so the if statment always happens as it effectivley becomes if(true){}.Hey guys, any help would be much appreciated. I've been having some real trouble with runtime errors with this code, mostly in that it seems as if no matter what you input, the answer is always correct. Not sure if it's just not generating a random number or if there's some other problem, but a look over would be much appreciated The game is a number guessing game #include <iostream> #include <time.h> class Game { public: Game(int topNumber); void PlayerGuesses(); void ComputerGuesses(); private: int m_topNumber; }; Game::Game(int topNumber) { m_topNumber = topNumber; time_t t; srand((unsigned int)time(&t)); } void Game::PlayerGuesses() { int r = rand(); int randomNumber; randomNumber = rand() %20+1; std::cout << "I have chosen a secret number between 1 and " << m_topNumber << "! Try to guess what it is..\n"; while (true) { int guess = 0; std::cin >> guess; if (guess = randomNumber) { std::cout << "Well done, you are right!\n"; continue; } else if (guess < randomNumber) { std::cout << "Too low!\n"; } else { std::cout << "Too high!\n"; } } } void Game::ComputerGuesses() { std::cout << "Choose a number between 1 and " << m_topNumber << "...\n"; int myGuess = m_topNumber / 2; int interval = myGuess / 2; while (true) { std::cout << "Is it " << myGuess << " ? (y/n)"; char c; std::cin >> c; if (c == 'y') { std::cout << "Har har!\n"; break; } std::cout << "Is your number higher or lower ? (h/l)"; std::cin >> c; if (c = 'h') { myGuess += interval; } else { myGuess += interval; } if (interval > 1) { interval /= 2; } } } int main() { Game g(20); while (true) { // Player must guess computer's number g.PlayerGuesses(); std::cout << "Now it's my turn!\n"; // Computer must guess player's number g.ComputerGuesses(); std::cout << "Would you like to play again ? (y/n)"; char c; std::cin >> c; if (std::cin == "n") { break; } } std::cout << "OK Bye!\n"; system("pause"); } |