Create a C++ program that generates a random number from 1 to 100 using the rand() function. Give the user a total 5 chances to guess the number. Stop the program and indicate the user guessed the correct number and should be applauded. Also, please find out which guess was the closest to the actual number. For example, if the rand() produces 57 and the user guessed 10, 80, 52, 33 and 44 in their respective turns then print out the user didn’t guess the number and should a 1 mile for closest guess (57 – 52 = 5 miles). (10 points)
NOTE: rand() and cin may or may not work in all the compilers, mostly in old compilers like turboc++ as it dont have header file for rand().
First we will calculate a random value and store it in the random int variable.
Then we will take user input using for loop. if input matches random value then will print message and break the loop else will go on taking inputs and storing in array.
After taking the inputs if no guess matches we move into the next part by checkig count==5 .
here we will calculate 1st shortest distance between 1st user guess and the random value generated. Then we will calculate temporat random value for the remaining guesses using a loop and check each with shortest in seacrh of new shortest. once we check for all the guesses we have the shortest distace so we print the required message.
----------------------------------------------------------------------------------code----------------------------------------------------------------------------
#include <iostream>
#include<conio>
using namespace std;
int main()
{
int random,num,i=0,count=0,shortest=0,temp;
int arr[5];
clrscr();
random = rand() % 100 + 1; //generating random number between 1 to
100;
for(i=0;i<5;i++)
{
cout<<"\nEnter the guess : ";
cin>>num;
if(num==random) ///checking for input as the random
number. if yes then breaking with output
{
cout<<"Congratulation you guessed the correct
number";
break;
}
else //else adding numbers into an array for future
use
{
arr[count]=num;
count++;
}
}
if(count==5) //if count is 5 then array is full means no guess was correct
{
if(arr[0]>random) //checking for bigger value
between random and 1st user input
//calculates shortest distance
{
shortest = arr[0]-random;
}
else
{
shortest =random-arr[0];
}
//calculateing temporary shortest distance between all guess and random
for(i=1;i<5;i++)
{
if(arr[i]>random)
{
temp = arr[i]-random;
}
else
{
temp = random-arr[i];
}
//comparing shortest value known to temporat shortest
if(temp<shortest)
{
shortest=temp;
}
}
//printing final output
cout<<"user did not guessed the number and
should a "<<shortest<<" mile for closest guess";
}
getch();
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.