Guess my number for the computer

I'm trying to reverse the guess my number program so that the user feeds the console a number and the computer has to guess it

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

int main()
{
int guess=0;
int number;
cout<<"Choose a number: "<<endl;
cin>>number;
int tries=0;
int scope=100;
do
{
;
guess=rand() % scope + 1;
cout<<guess<<endl;
tries++;

if (guess > number)
{ cout<<"number too high "<<endl;
scope=guess-(rand()%(scope-guess));
<--------------->don't know how to make it pick a number smaller than the last one

}

if (guess< number)
{
cout<<"number too low" <<endl;
scope=guess+ (rand()%(scope-guess));
<--------------->don't know how to make it pick a number bigger than the last one

}

}while(guess!=number);
cout<<"You guess right in "<<tries<<"tries";
system("PAUSE");
return 0;


how should I make it choose a bigger/smaller number

Thanks in advance !
closed account (j3bk4iN6)
try iterating through the range until the computer finds it. Takes the fun out of it though.
Id also like to say if you take a binary tree approach you can divide the search by 2 and cut the binarysearch in half each time.
Last edited on
closed account (jLNv0pDG)
You could try setting High / Low values and having the computer guess a number between those values. Then if it guesses too high / low you can just adjust the highest and lowest possible numbers from there.

Possibly something along the lines of:

1
2
3
4
5
6
7
8
9
10
int high = 100;
int low = 0;

guess = rand() % ( high - low ) + low;

if (guess < target)
	low = guess + 1

if (guess > target)
	high = guess - 1
Last edited on
Also use code tags please and proper tabbing/newlines.
Topic archived. No new replies allowed.