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 36 37 38 39 |
#include <iostream> #include <cstdlib> #include <ctime> int main() { // Seed the random number generator std::srand(std::time(0)); // Define the range for the random number const int MIN_NUMBER = 1; const int MAX_NUMBER = 100; // Generate a random number within the range int randomNumber = MIN_NUMBER + std::rand() % (MAX_NUMBER - MIN_NUMBER + 1); int guess; bool hasGuessedCorrectly = false; std::cout << "Welcome to the Number Guessing Game!" << std::endl; std::cout << "Guess the number between " << MIN_NUMBER << " and " << MAX_NUMBER << ": " << std::endl; while (!hasGuessedCorrectly) { std::cout << "Enter your guess: "; std::cin >> guess; if (guess < MIN_NUMBER || guess > MAX_NUMBER) { std::cout << "Please enter a number between " << MIN_NUMBER << " and " << MAX_NUMBER << "." << std::endl; } else if (guess < randomNumber) { std::cout << "Too low! Try again." << std::endl; } else if (guess > randomNumber) { std::cout << "Too high! Try again." << std::endl; } else { std::cout << "Congratulations! You guessed the number!" << std::endl; hasGuessedCorrectly = true; } } return 0; } |
Explanation:
- Random Number Generation:
std::srand(std::time(0));
seeds the random number generator using the current time to ensure different sequences of random numbers on each run.std::rand()
generates a random integer. By scaling and shifting it, we get a number within the desired range.int randomNumber = MIN_NUMBER + std::rand() % (MAX_NUMBER - MIN_NUMBER + 1);
generates a random number betweenMIN_NUMBER
andMAX_NUMBER
(inclusive).
- Game Logic:
- Input Validation: The program ensures that the player’s guess is within the specified range (
MIN_NUMBER
toMAX_NUMBER
). - Feedback: Provides feedback if the guess is too low or too high, guiding the player to adjust their guess.
- Completion Check: When the guess matches the random number, the player is congratulated, and the game loop exits.
- Input Validation: The program ensures that the player’s guess is within the specified range (
- User Interaction:
- The player is prompted to guess the number.
- The game continues to prompt for guesses until the correct number is guessed.