1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { // Initialize random seed srand(static_cast<unsigned int>(time(0))); const int MIN = 1; const int MAX = 100; int targetNumber = rand() % (MAX - MIN + 1) + MIN; int guess; int attempts = 0; cout << "Welcome to 'Guess the Number' game!" << endl; cout << "I'm thinking of a number between " << MIN << " and " << MAX << "." << endl; do { cout << "Enter your guess: "; cin >> guess; ++attempts; if (guess > targetNumber) { cout << "Too high! Try again." << endl; } else if (guess < targetNumber) { cout << "Too low! Try again." << endl; } else { cout << "Congratulations! You guessed the number in " << attempts << " attempts." << endl; } } while (guess != targetNumber); return 0; } |
Explanation:
- Random Number Generation:
srand(static_cast<unsigned int>(time(0)))
seeds the random number generator with the current time to ensure different results on each run.rand() % (MAX - MIN + 1) + MIN
generates a random number betweenMIN
andMAX
.
- Game Loop:
- The
do-while
loop continues until the player guesses the correct number. cin >> guess
reads the player’s guess from the standard input.- If the guess is too high, the program informs the player to guess lower.
- If the guess is too low, the program informs the player to guess higher.
- If the guess is correct, the program congratulates the player and displays the number of attempts taken.
- The
- Variables:
targetNumber
: Stores the randomly generated number the player needs to guess.guess
: Stores the player’s current guess.attempts
: Counts the number of guesses made by the player.
- User Interaction:
- The program interacts with the player through
cout
andcin
, providing feedback and prompting for guesses.
- The program interacts with the player through
Possible Enhancements:
- Input Validation: Ensure the player inputs a valid number within the specified range.
- Difficulty Levels: Add difficulty levels by changing the range of numbers or the number of allowed attempts.
- Replay Option: Allow the player to play multiple rounds without restarting the program.
- Hints: Provide hints or a range of numbers that are closer to the target number as guesses are made.