C++ 定义一个计数器类,完成倒计时的功能。

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 !!!" <

3.测试程序功能。

int main()
{
	//测试计数器类 
	system("color  f1");
	int hour_;
	int minute_;
	int second_;
	cout << "Please enter the time ! " << endl;
	cout << "hour : "  <> hour_;
	cout << "minute : "<> minute_;
	cout << "second : "<> second_;
	cout << endl;
	Counter text1(hour_,minute_,second_);
	text1.countDown();
    return 0;
}

完整代码如下:

#include
#include
#include
#include
#include
#include
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 !!!" <> hour_;
	cout << "minute : "<> minute_;
	cout << "second : "<> second_;
	cout << endl;
	Counter text1(hour_,minute_,second_);
	text1.countDown();
    return 0;
}

你可能感兴趣的:(C++,1024程序员节,c++,算法,开发语言)