Grupo
Programación en Tiempo Real en C++
Ojetivo
Escriba un programa en C++ que reciba un número como entrada del usuario y realice una cuenta regresiva hasta 0, actualizándose cada segundo. Use un bucle para decrementar el número y mostrar la cuenta regresiva en la consola. Asegúrese de que el programa espere un segundo entre cada actualización.
Implemente un temporizador de cuenta regresiva que cuente desde un número específico hasta 0.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the input-output stream library
#include <thread> // Include the thread library to implement delays
#include <chrono> // Include the chrono library for time-related functions
using namespace std;
// Function to implement the countdown timer
void countdown(int start) {
while (start >= 0) { // Loop until the start number reaches 0
// Display the current countdown number
cout << "\r" << start << flush;
// Wait for 1 second before the next countdown
this_thread::sleep_for(chrono::seconds(1));
// Decrease the countdown number by 1
start--;
}
cout << "\nCountdown finished!" << endl; // Notify when countdown is complete
}
int main() {
int number;
cout << "Enter a number to start the countdown: ";
cin >> number; // Input a starting number for the countdown
// Call the countdown function with the input number
countdown(number);
return 0;
}
Salida
Enter a number to start the countdown: 5
5
4
3
2
1
0
Countdown finished!
Comparte este ejercicio C++