Untitled
#include <iostream> #include <cstdlib> // For random number generation #include <ctime> // For time functions to seed the random number generator using namespace std; int main() { // Seed the random number generator with the current time srand(time(0)); // Generate a random number between 1 and 100 int numberToGuess = rand() % 100 + 1; int userGuess = 0; int numberOfTries = 0; cout << "Welcome to the Number Guessing Game!" << endl; cout << "I have selected a number between 1 and 100." << endl; cout << "Can you guess what it is?" << endl; // Loop until the player guesses the number correctly while (userGuess != numberToGuess) { cout << "Enter your guess: "; cin >> userGuess; // Take user input numberOfTries++; // Increment the number of tries if (userGuess > numberToGuess) { cout << "Too high! Try again." << endl; } else if (userGuess < numberToGuess) { cout << "Too low! Try again." << endl; } else { cout << "Congratulations! You've guessed the correct number: " << numberToGuess << endl; cout << "It took you " << numberOfTries << " tries to guess the number." << endl; } } return 0; }
Leave a Comment