Number guessing

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Guess My Number
// The classic number guessing game

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(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;
	    }

	    else if (answer == 1)           //If answer is too low
	    {
	        compGuess = rand() % compGuess + compGuess + 1;
	    }

	    else if (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?
Last edited on
@Fovv

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;
@whitenite1

Thank you very much for the help. The program works as intended :D
Topic archived. No new replies allowed.