源代码(含解析)
#include <iostream> //系统输入流
#include <conio.h> //用于键盘检测
#include <Windows.h>//用于Sleep();
//标准命名空间
using namespace std;
//正计时函数
void Time01()
{
bool pause = false;
int s = 0;
int m = 0;
cout << "Press anything to start." << endl;
getch();
while (1)
{
if (kbhit())
{
char input = getch();
//按空格暂停和继续
if (input == ' ') pause = !pause;
//按Esc退出
else if (input == 27)
{
cout << "Stop." << endl;
break;
}
}
//正常计时
else if (!pause)
{
//清屏
system("cls");
//显示当前时间
cout << "Time:" << m << ":" << s << endl << "Press space to pause.\nPress Esc to stop." << endl;
s++;
//更新分钟数m
if (s == 60)
{
s = 0;
m++;
}
Sleep(1000);
}
}
getch(); //按任意键继续
}
//倒计时函数
void Time02()
{
bool pause = false;
int s = 0; //秒数
int m = 0; //分钟数
cout << "Enter the minutes:";
cin >> m;
cout << "Enter the seconds:";
cin >> s;
system("cls");
cout << "Press anything to start." << endl;
getch();
while (1)
{
if (kbhit())
{
//获取键盘输入
char input = getch();
//空格暂停与继续
if (input == ' ') pause = !pause;
//Esc退出
else if (input == 27)
{
cout << "Stop." << endl;
break;
}
}
//正常计时
else if (!pause)
{
system("cls");
cout << "Time:" << m << ":" << s << endl << "Press space to pause.\nPress Esc to stop." << endl;
s--;
if (s == -1 && m > 0)
{
s = 59;
m--;
}
//计时结束
else if (s == -1 && m == 0)
{
cout << "\a\a\a\a\aTime's up." << endl;
break;
}
Sleep(1000);
}
}
getch();
}
int main()
{
system("title Timer");
cout << "Timer" << endl;
cout << "Press anything to begin.";
getch();
system("cls");
cout << "\aChoose mod.\n1.Positive timing 2.countdown" << endl << ">>>";
int mod;
cin >> mod;
switch(mod)
{
case 1: Time01(); break;
case 2: Time02(); break;
}
return 0;
}