1.首先,在构造函数内进行初始化,并规定小于零则重置为零。
Counter(int h,int m,int s)
{
if(h<0)
{
hour=0;
}
else if(m<0)
{
minute=0;
}
else if(s<0)
{
second=0;
}
else
{
hour=h;
minute=m;
second=s;
}
}
2.在函数countDown()内实现倒计时的功能。
void countDown()
{
for( i=hour;i>=0;i--)
{
for( j=minute;j>=0;j--)
{
for( k=second;k>=0;k--)
{
long temp=time(NULL);
while(time(NULL)==temp);
if(--second<=0)
{
second=59;
if(--minute<=0)
{
minute=59;
if(--hour<=0)
{
hour=23;
}
}
}
Sleep(1000);
system("cls");
cout << "The remaining time is ";
if(i<10)
cout << "0";
cout << i << " : ";
if(j<10)
cout << "0";
cout << j << " : ";
if(k<10)
cout << "0";
cout << k << endl;
}
}
}
system("color f4");
cout<<"Time is up !!!" <<endl;
system("pause");
}
3.测试程序功能。
int main()
{
//测试计数器类
system("color f1");
int hour_;
int minute_;
int second_;
cout << "Please enter the time ! " << endl;
cout << "hour : " <<endl;
cin >> hour_;
cout << "minute : "<<endl;
cin >> minute_;
cout << "second : "<<endl;
cin >> second_;
cout << endl;
Counter text1(hour_,minute_,second_);
text1.countDown();
return 0;
}
完整代码如下:
#include<iostream>
#include<cstdlib>
#include<windows.h>
#include<cstring>
#include<ctime>
#include<math.h>
using namespace std;
//计数器类
class Counter
{
public:
Counter(int h,int m,int s)
{
if(h<0)
{
hour=0;
}
else if(m<0)
{
minute=0;
}
else if(s<0)
{
second=0;
}
else
{
hour=h;
minute=m;
second=s;
}
}
void countDown()
{
for( i=hour;i>=0;i--)
{
for( j=minute;j>=0;j--)
{
for( k=second;k>=0;k--)
{
long temp=time(NULL);
while(time(NULL)==temp);
if(--second<=0)
{
second=59;
if(--minute<=0)
{
minute=59;
if(--hour<=0)
{
hour=23;
}
}
}
Sleep(1000);
system("cls");
cout << "The remaining time is ";
if(i<10)
cout << "0";
cout << i << " : ";
if(j<10)
cout << "0";
cout << j << " : ";
if(k<10)
cout << "0";
cout << k << endl;
}
}
}
system("color f4");
cout<<"Time is up !!!" <<endl;
system("pause");
}
private:
int hour;
int minute;
int second;
int i,j,k;
};
int main()
{
//测试计数器类
system("color f1");
int hour_;
int minute_;
int second_;
cout << "Please enter the time ! " << endl;
cout << "hour : " <<endl;
cin >> hour_;
cout << "minute : "<<endl;
cin >> minute_;
cout << "second : "<<endl;
cin >> second_;
cout << endl;
Counter text1(hour_,minute_,second_);
text1.countDown();
return 0;
}