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>(time(0))); // Generate a random number between 1 and 100 int numberToGuess = rand() % 100 + 1; int userGuess = 0; int numberOfTries = 0; cout << "Welcome to Guess the Number Game!" << endl; cout << "I have selected a number between 1 and 100." << endl; cout << "Can you guess what it is?" << endl; while (userGuess != numberToGuess) { cout << "Enter your guess: "; cin >> userGuess; numberOfTries++; if (userGuess > numberToGuess) { cout << "Too high! Try again." << endl; } else if (userGuess < numberToGuess) { cout << "Too low! Try again." << endl; } else { cout << "Congratulations! You guessed the number in " << numberOfTries << " tries." << endl; } } return 0; } |
Explanation
- Initialize Random Seed:
srand(static_cast<unsigned>(time(0)));
initializes the random number generator with the current time to ensure different sequences of random numbers each time the program runs.
- Generate Random Number:
int numberToGuess = rand() % 100 + 1;
generates a random number between 1 and 100 for the player to guess.
- Game Loop:
- The loop continues until the player guesses the correct number.
- The user is prompted to enter a guess.
- The program checks if the guess is higher or lower than the target number and provides feedback.
- The number of attempts is tracked and displayed once the correct number is guessed.
- End Game:
- When the user guesses correctly, the program congratulates the player and displays the number of attempts taken.