mardi 15 mars 2016

trouble with random guessing game in c++

So I need to do a Guessing game where the program generates a random number and the user has to guess the number. if the user guesses the number in less than 10 guesses the program congratulates them and lets them know they were under 10 guesses. if they were above 10 guesses then it lets them know it was above 10, etc.

the problem i'm facing is if, for example, the user guesses the number in 3 tries and then decides to play again with a whole new other number, and this time guesses it in 8 tries, instead of still congratulating them because it was under 10 tries, it counts the 3 tries from the previous game. This then leads the program to tell them they were over 10 tries, even though they were not. i don't know how to fix this. the code I've done so far is as follows:

#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>

int main()
{
   srand(time(0));
   int guess;
   int number;
   char selection = 'y';
   int numberOfGuesses=0;

 while(selection == 'y' || selection == 'Y')
 {
      number = rand() % 1000 + 1;

      cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess: ";
      cin >>guess;

      do
      {
         if(number > guess)
         {
            cout << "Too low. Try again: " << endl;
            cin >> guess;
            numberOfGuesses++;
         }
         if (number < guess)
         {
            cout << "Too high. Try again: " << endl;
            cin >> guess;
            numberOfGuesses++;
         }

      } 

      while(number != guess);

      if(numberOfGuesses < 9)
      {
            cout << "Excellent! You guessed the number in less than 10 guesses! Either you know the secret, or you got lucky!\n Would you like to play again (y or n)?";
            cin >> selection;
      }
      else if(numberOfGuesses > 9)
      {
            cout << "You guessed the number, but you should be able to do better!\n Would you like to play again (y or n)?";
            cin >> selection;
      }

      else if(numberOfGuesses == 9)
      {
            cout << "Ahah! You know the secret! You guessed the number.\n Would you like to play again (y or n)?";
            cin >> selection;
      }

  }

   return 0;
 }




Aucun commentaire:

Enregistrer un commentaire