I am starting back up on my C++ programming and I've been out of it for about 3 years. I am going back through one of my books and it asks you to create a game.
Guess My Number:
-Player picks number 1-100
-Computer proceeds to guess a number till it hits the number you chose
-Be creative!
I have already written the program about 30 min ago and after some trial and error, it seems to be working except for:
-Kinda sloppy/redundant
-Once the computer guesses the correct number, it skips the output of the correct number and proceeds the the end of the program.
Code:
//Guess My Number
//Dustin Hardin 12-08-09
/* The Player picks a number between 1 and 100 and the
computer guesses till it gets it right. */
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int theNumber;
int tries = 0, guess, prevGuessHigh = 100, prevGuessLow = 1;
cout << "\tWelcome to Guess My Number\n\n";
cout << "Player, please pick a number between 1 and 100: ";
cin >> theNumber;
cin.ignore();
//Generate "random" number between 1 and 100 as computers guess
srand(time(0));
guess = rand() % 100 + 1;
do
{
//display previous input, the number you picked, and ask for a number.
cout << "High: " << prevGuessHigh << ", Low: " << prevGuessLow << ", The Number: " << theNumber << "\n\n";
cout << "Computer, please guess a number: " << guess << "\n\n";
cin.get();
++tries;
if(guess > theNumber)
{
cout << "Too High!\n\n";
prevGuessHigh = guess;
guess = rand() % (prevGuessHigh - prevGuessLow) + prevGuessLow; //the number is between the high guess and low, so random between these two
if(guess == prevGuessLow)//Increment guess if it's equal to the last lowest number
guess++;
}
else if(guess < theNumber)
{
cout << "Too Low!\n\n";
prevGuessLow = guess;
guess = rand() % (prevGuessHigh - prevGuessLow) + prevGuessLow; //the number is between the high guess and low, so random between these two
if(guess == prevGuessLow)//Increment guess if it's equal to the last lowest number
guess++;
}
}while(guess != theNumber);
cout << "That's it! You got it in: " << tries << " guesses!";
cout << "\n\nPlease press the enter key to exit....";
cin.get();
return 0;
}