Grupo
Estructuras Condicionales Avanzadas en C++
Ojetivo
1. Genere un número aleatorio entre 1 y 100.
2. Pida al usuario que adivine el número.
3. Compare la suposición del usuario con el número generado.
4. Ofrezca retroalimentación si la suposición es demasiado alta, demasiado baja o correcta.
5. Continúe pidiendo suposiciones hasta que el usuario adivine el número correcto.
6. Muestre el número de intentos que el usuario tardó en adivinar correctamente.
Implemente un programa que simule el juego de adivinar números (rango 1-100).
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include input/output stream
#include <cstdlib> // For random number generation
#include <ctime> // For seeding the random number generator
using namespace std;
int main() {
srand(time(0)); // Seed the random number generator with the current time
int targetNumber = rand() % 100 + 1; // Generate a random number between 1 and 100
int guess; // Variable to store the player's guess
int attempts = 0; // Counter for the number of attempts
// Introduce the game to the user
cout << "Welcome to the Guess the Number Game! The number is between 1 and 100.\n";
// Start the game loop
do {
cout << "Enter your guess: "; // Prompt the user to enter a guess
cin >> guess; // Store the user's guess
attempts++; // Increment the attempt counter
if (guess < targetNumber) {
cout << "Your guess is too low. Try again.\n"; // If guess is too low, provide feedback
} else if (guess > targetNumber) {
cout << "Your guess is too high. Try again.\n"; // If guess is too high, provide feedback
} else {
cout << "Congratulations! You've guessed the number in " << attempts << " attempts.\n"; // If guess is correct, congratulate the user
}
} while (guess != targetNumber); // Continue the loop until the correct guess is made
return 0; // Return 0 to indicate successful completion of the program
}
Salida
Welcome to the Guess the Number Game! The number is between 1 and 100.
Enter your guess: 50
Your guess is too high. Try again.
Enter your guess: 25
Your guess is too low. Try again.
Enter your guess: 37
Your guess is too low. Try again.
Enter your guess: 43
Your guess is too low. Try again.
Enter your guess: 47
Your guess is too high. Try again.
Enter your guess: 45
Congratulations! You've guessed the number in 6 attempts.
Comparte este ejercicio C++