In: Computer Science
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)
don't use arrays please
Program Code Screenshot :
Sample Output :
Program Code to Copy
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
//Start seed
srand(time(0));
//Generate a random number below 100
int gen = rand()%100+1;
int u;
int ans = 101;
bool found = false;
//Read 5 user input numbers
for(int i=0;i<5;i++){
cin>>u;
//If guessed correctly, exit the loop
if(gen==u){
found = true;
break;
}
//update the number closeset to the guess
if(abs(gen-u)<ans){
ans = u;
}
}
//Check if correctly guessed
if(found){
cout<<gen<<" guessed correctly"<<endl;
}
//Print the closest guess
else{
cout<<"The closest guess to "<<gen<<" is
"<<ans<<endl;
}
return 0;
}