You are here:

C++/c++ guessing game problem

Advertisement


Question
i have written this program for class but am stuck.  i need to make sure the user has 10 chances(which i did)and after the user runs out of guesses or guesses the number correctly, the program should ask if they want to play again and react accordingly.  at the end of the program it should display some summary info, including number of games played, number of correct guesses and average number of of guesses it took to get the right answer.  this is my first c++ programming class and i am still alittle shaky.  any help would greatly be appreciated.  here is what i have so far:
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main ()
{
  int num;
  int guess;
  bool done;
  int noOfGuesses = 0;
  int ncount;
  num = (rand() + time(0)) % 1000;
  done = false;
  while ((noOfGuesses < 10) && (!done))
  
  {
     cout << "Enter an integer greater"
        << " than or equal to 0 and "
        << "less than 1000: ";
     cin >> guess;
     cout << endl;
     noOfGuesses++;
     if (guess == num)
     {
        cout << "you guessed the correct "
         << "number." << endl;
        done = true;
     }
     else
        if (guess < num)
        cout << "Your guess is lower "
         << "than the number. \n"
         << "Guess again!" << endl;
        else
         cout << "Your guess is higher "
         << "than the number.\n"
         << "guess again!" << endl;
        cout <<"Total guesses equal "
         <<  noOfGuesses << endl;


     
  }
  return 0;
  }


Answer
int main ()
{
int num;
int guess, icorrectguess = 0;
bool done;
int noOfGuesses = 0;
int ncount;
num = (rand() + time(0)) % 1000;
done = false;

while ((noOfGuesses < 10) )

{
cout << "Enter an integer greater"
<< " than or equal to 0 and "
<< "less than 1000: ";
cin >> guess;
cout << endl;
noOfGuesses++;

         
if (guess == num)
{
cout << "you guessed the correct "<< "number." << endl;
icorrectguess++;
}

if (guess < num)
  cout << "Your guess is lower "    << "than the number. \n"    << "Guess again!" << endl;
if(guess > num)
   cout << "Your guess is higher "<< "than the number.\n"<< "guess again!" << endl;
if(noOfGuesses == 10)
{
     cout<<" Please enter y to play again or Q to quit";
     char temp;
     cin>>temp;
     if((temp  == 'Y') || (temp == 'y'))
     noOfGuesses =0;
}

}

cout <<"Total guesses equal " <<  noOfGuesses << endl << "Total number of correct guess=" << icorrectguess;

return 0;
}
I have made some minor modifications. Let me know if this will not work!

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


rakshitha

Expertise

Difficult questions related to C .

Experience

C ,vc ,opc ,windows CE, ActiveX

Education/Credentials
Masters in electrical engineering

©2016 About.com. All rights reserved.