Respuesta :
Answer:
A C++ program was used for a user or the computer play a guessing game.
Explanation:
The C++ code to this question:
#include <iostream>
#include <cstdlib> // srand and rand functions
#include <ctime> // time function
using namespace std;
int main()
{
const int C = 100;// constant integer with defined value 100
char type;// type of option chosen
cout<<"Would you like to (p)lay or watch the (c)omputer play?"<<endl;
cin>>type;// input of type
do{// for first iteration you can't choose q
int x;
srand(unsigned(time(NULL))); // set different seeds to make sure each run of this program will generate different random numbers
x = ( rand() % C);
x++;// random value between 1 and 100
int check=-1;// make initial check=-1
int ends=C;// for type selected as c, make the initial guess to be chosen from 1 to 100
int start=1;
while(1)
{
if(type=='p')// if selected type is p
{
cout<<"Enter your guess in between 1 and 100."<<endl;
cin>>check;
}
else if(type=='c')// if selected type is c
{
check=start+(rand()%(ends-(start-1)));//get a random number between updated start and ends for computer guessing
cout<<"The computer's guess is "<<(check)<<"."<<endl;
}
else// if type is not equal to c or p or q
{
cout<<"Invalid option chosen"<<endl;
break;
}
if(check>x)// if the guess is greater
{
cout<<"Sorry, your guess is too high, try again."<<endl;
ends=check-1;// update ends in case type is c
}
else if(check<x)
{
cout<<"Sorry, your guess is too low, try again."<<endl;
start=check+1;// update start
}
else// if right number is selected
{
cout<<"Congrats, you guessed the correct number, "<<x<<"."<<endl;
break;
}
}
cout<<"Would you like to (p)lay or watch the (c)omputer play or (q)uit?"<<endl;
cin>>type;
}while(type!='q');
return 0;
}
Note: Kindly find an attached copy of the screenshot of execution of code below