I'm currently learning c++ from "Beginning C++ through game programming"
One of the exercises was to edit a program to have the computer guess your number instead of you guessing the computer's number. This is what I have so far
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(static_cast<unsignedint>(time(0))); //seed random number generator
int compGuess = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int answer;
bool guess;
cout<<"\tWelcome to Guess your Number!\n";
cout<<"\tThink of a number between 1 and 100.\n\n";
do
{
cout<<"My guess is "<<compGuess <<"\n\n";
cout<<"Is this: \n";
cout<<"1: Too low\n";
cout<<"2: Too high\n";
cout<<"3: correct\n";
cin>>answer;
++tries;
guess = false;
if (answer == 2) //If answer is too high
{
compGuess = rand() % compGuess + 1;
}
elseif (answer == 1) //If answer is too low
{
compGuess = rand() % compGuess + compGuess + 1;
}
elseif (answer == 3)
{
cout<<"I win! It only took me " << tries << " guesses!\n";
guess = true;
}
}while(!guess);
}
The program works in that if it guessed too low, it will guess a higher number and if it guessed too high it will guess a lower number. The problem is it will guesses completely random numbers below or above the previous number.
My question is this:
a) Is there a way to make it guess based off of previous guesses?
b) Is there a better way of limiting the range of the rand() than the module?
Create a couple more variables. int lo = 0; hi = 100; When the computer guesses, and the guess was to high, assign variable hi, to that guess, and the same if the guess was to low. Then the computer guess would be compGuess = rand() % (hi-low+1)+low;