In: Computer Science
#include <iostream>
using namespace std;
int main()
{
srand (time(NULL)); // initializing random number generator
int randomMile; //variables for storing random mile value,
int minDiffMile = 100; //minimum random mile value,
int userInputMile = 0; //user input mile
int closestGuess = 0;
randomMile = 1 + rand() % 100; //generate a random number 1 to 100
for (int i = 5; i > 0; --i) { //loop running 5 times for 5 guesses
cout << "Guess a number" << '\n';
cin >> userInputMile; //taking input
if (userInputMile == randomMile) //if user guesses the number right
{
cout << "You guessed it RIGHT" << '\n'; //print to display
return 0; //return if user guessed it right
}
else{ //else the guess is wrong
cout << "You guessed it WRONG, Try left: "+to_string(i-1) << '\n';
//calculation the difference between random mile and and user input
int diffMile = (randomMile < userInputMile) ? (userInputMile - randomMile) : (randomMile - userInputMile);
//storing difference to minDiffMile if it is lesser than previously stored value and storing closest guess
if (diffMile < minDiffMile)
{
closestGuess = userInputMile;
minDiffMile = diffMile;
}
}
}
//if user guessed 5 times wrong then program has not returned, hence reached this line
cout << "Closest guess was: " + to_string(closestGuess) << '\n'; //printing closest guess
cout << "and difference from closest guess is: " + to_string(minDiffMile) << '\n'; //printing diff
return 0;
}
CODE SNIPPET
Sample output 1 (When user guessed it right)
Sample output 1 (When user guessed it wrong for 5 times)