I started coding C++ this past week, and yesterday I challenged myself to write something original that my book doesn't have hints on. It is a program that prompts the user to think of a number between 1 and 100, and proceeds to guess the user's number. The user tells the program whether it's guess is too high or too low, and the computer uses that information to refine its guess until it has the right number. I have tried several different ideas on how to set the limits which the computer must guess within, but nothing seems to work. This is what I have right now. It compiles and runs just fine, but is a terrible guesser. If I say it's too high, it goes lower, but if I say it's too low, it gives me a seemingly random number. I have a feeling this is a simple mathematical error and I'm really over-thinking this, but any help would be appreciated. Also, please go easy on me if my code is super inefficient or convoluted, it's my fourth day :
Don't know why all the colors got screwed up
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int setLimits(int, int, int);
int main()
{
char guessCorrect;
char playAgain;
srand(static_cast<unsigned int>(time(0)));
int tries = 0;
int computerGuess;
int highLimit = 100;
int lowLimit = 1;
cout<<"\n\t\t**Welcome, I am the psychic computer!**";
cout<<"\n\nThink of a number between 1 and 100.";
cout<<"\nReady? (y/n):";
cin>>playAgain;
do
{
if (playAgain == 'y')
{
computerGuess = (rand() % 100) + 1;
do
{
++tries;
cout<<"\nAre you thinking of the number "<<computerGuess<<"? (y/n):";
cin>>guessCorrect;
if (guessCorrect == 'y')
{
break;
}
else
{
computerGuess = setLimits(computerGuess, lowLimit, highLimit);
}
}while (guessCorrect != 'y');
cout<<"\nI guessed your number in "<<tries<<" tries!";
cout<<"\nPlay again? (y/n):";
cin>>playAgain;
}
else
{
continue;
}
}while (playAgain == 'y');
cout<<"\nGoodbye!";
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
int setLimits(int computerGuess, int lowLimit, int highLimit)
{
char tooHigh;
cout<<"\nDid I guess too high? (y/n)";
cin>>tooHigh;
if (tooHigh == 'y')
{
highLimit = computerGuess-1;
computerGuess = ((rand() % (computerGuess-1))+1);
if (computerGuess < lowLimit)
{
computerGuess = (computerGuess + ((lowLimit - computerGuess)+1));
}
}
else
{
lowLimit = highLimit-(highLimit-computerGuess);
computerGuess = ((rand() % (highLimit-lowLimit))+lowLimit);
if (computerGuess > highLimit)
{
computerGuess = (computerGuess - ((highLimit - computerGuess)-1));
}
}
return computerGuess;
}