c++倒计时代码
cpp#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void countdown(int seconds) {
for (int i = seconds; i > 0; --i) {
cout << "Remaining: " << i << " seconds..." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
cout << "Time's up!" << endl;
}
int main() {
int seconds;
cout << "Enter the number of seconds for countdown: ";
cin >> seconds;
countdown(seconds);
return 0;
}
这个程序接受用户输入的秒数,然后开始倒计时,每秒输出剩余时间,直到倒计时结束。
在这个程序中,我们使用了 <chrono> 库来处理时间,<thread> 库来实现暂停功能。chrono::seconds(1) 表示等待1秒钟。
你可以根据需要进行修改和扩展,比如添加声音提示或者在倒计时结束时执行其他操作。
cpp#include <iostream>
#include <chrono>
#include <thread>
#include <cstdlib> // For system() function
using namespace std;
void countdown(int seconds) {
for (int i = seconds; i > 0; --i) {
cout << "Remaining: " << i << " seconds..." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
cout << "Time's up!" << endl;
// Add additional operations after countdown
cout << "Performing additional operations..." << endl;
// For demonstration, we will play a system beep sound
cout << '\a'; // Beep sound
}
int main() {
int seconds;
cout << "Enter the number of seconds for countdown: ";
cin >> seconds;
countdown(seconds);
return 0;
}
在这个版本中,倒计时结束后会发出系统蜂鸣声。这是通过在 cout 中输出 '\a' 实现的,它会触发系统默认的蜂鸣声。
你也可以通过调用系统命令来播放音频文件或者调用其他外部程序来执行特定操作,具体取决于你的需求和操作系统支持的功能。