Write a program that plays a number guessing game with a human user. The human user will think of a number between 1 and 100, inclusive. Then the program has to guess what the user entered. keep track of the number of interaction it takes for the computer to guess the number.
sample run:
enter number to be guessed:88
output: you entered 88, and it took the program 3 iterations to guess.
#include <iostream>
using namespace std;
const int MAX_VALUE = 100;
const int MIN_VALUE = 0;
int guess;
int high = MAX_VALUE;
int low = MIN_VALUE;
char choice;
int main(){
cout<<"Think about a number between "<<MIN_VALUE<<" and "<<MAX_VALUE<<". \n\n";
guess = ( high-low ) / 2;
while(guess>low){
cout<<"Is your number less than or equal to "<<guess<<"? \nEnter y or n. \n\n";
cin>>choice;
if(choice=='y' || choice=='Y') {
high = guess;
if(high-low==1) guess=low;
else guess -= ( high - low ) / 2;
}
else if(choice=='n' || choice=='N') {
low = guess;
guess += (high - low ) /2;
}
else cout<<"Incorrect choice."<<endl;
}
cout<<"Your number is: "<<high<<".\n";
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.