用定时器和计数器实现可正/倒记时的秒表
时间: 2024-03-09 18:47:46 浏览: 25
好的,以下是一个用定时器和计数器实现可正/倒记时的秒表的示例代码:
```c++
#include <iostream>
#include <windows.h>
using namespace std;
void displayTime(int time) {
int hour, minute, second;
hour = time / 3600;
minute = (time % 3600) / 60;
second = (time % 3600) % 60;
printf("%02d:%02d:%02d", hour, minute, second);
}
void stopwatch(int seconds, bool countUp) {
int time = 0;
while (time <= seconds) {
displayTime(time);
cout << endl;
Sleep(1000);
if (countUp) {
time++;
} else {
time--;
}
}
}
int main() {
int seconds;
bool countUp;
cout << "Please enter the number of seconds: ";
cin >> seconds;
cout << "Do you want to count up? (1 for yes, 0 for no): ";
cin >> countUp;
stopwatch(seconds, countUp);
return 0;
}
```
这个程序可以让用户输入秒数和计时方向(正计时或倒计时),然后使用 `displayTime` 函数将秒数转换为时分秒格式并输出,使用 `Sleep` 函数暂停 1 秒钟来模拟计时器,使用 `countUp` 参数控制计时方向。