Objective: To introduce functions through the system built-in function randO whi
ID: 3802144 • Letter: O
Question
Objective: To introduce functions through the system built-in function randO which generates a random number between 1 and the system value RAND MAX, srand0 which sets the starting seed value, and time0 which computes the current time in seconds. To further our understanding of loops, their logic and the correct use of the while() do and while for control structures in the C++ programming language. Specifically to show an understanding of the logically appropriate use of nested loops and embedded conditional statements. To reinforce our understanding of data types and variables. Namely, how to create, initialize, display and perform basic arithmetic operations on those variables. Assignment: Write a program that allows the user to try and guess a number that has been randomly generated using the rand0 function. Your program shoul generate a random number from within some specified range (e.g. 1 1000) and then prompt the player to try and guess the number that was generated. Note to use the C++ random number function, your program must include the cstdlib and, to use the time function, your program must include ctime. See the following sample program to generate a random number between 1 and 10 inclusive.Explanation / Answer
PROGRAM CODE:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int generateNumber(int min, int max)
{
return min + rand()%max;
}
bool compare(int value1, int value2)
{
return value1 == value2;
}
int main() {
int count = 0;
srand(time(0));
int randomNumber = generateNumber(1, 1000);
int guess;
char choice;
cout<<"I have a number between 1 and 1000. Can you guess my number? Please enter your first guess: ";
cin>>guess;
if(compare(randomNumber, guess))
{
cout<<" WOW, either you are insightful or got really lucky!";
cout<<" Would you like to play again?";
cin>>choice;
}
else
{
if(randomNumber > guess)
cout<<" Too Low. Try again(Y/N): ";
else
cout<<" Too High. Try again(Y/N): ";
cin>>choice;
}
count++;
while(choice == 'Y' || choice == 'y')
{
cout<<" Enter your guess: ";
cin>>guess;
count++;
if(count == 10 && compare(randomNumber, guess))
{
cout<<" Ahan! 10th time lucky!";
cout<<" Would you like to play again?";
}
else if(count == 12 && !compare(randomNumber, guess))
{
cout<<"Really, you honestly can do better than 12 guesses!";
cout<<" Would you like to play again?";
}
else if(randomNumber > guess)
cout<<" Too Low. Try again(Y/N): ";
else
cout<<" Too High. Try again(Y/N): ";
cin>>choice;
}
return 0;
}
OUTPUT:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.