C++命令符式倒计时程序

要求:输入时间进行计时。

代码如下:

#include<iostream>
#include<ctime>
#include<unistd.h>
using namespace std;

class Time{
    private:
        int h;//小时
        int m;//分钟
        int s;//秒
    public:
        Time(int hour,int min,int sec);//构造函数
        void run();//运行
        void show();//显示
};

Time::Time(int hour,int min,int sec)//构造函数赋初值
{
    h = hour;
    m = min;
    s = sec;
}

void Time::show()
{
    cout << '\r';//全部显示在同一行
    if(this->h<10) cout << 0;
    cout << this->h << ':';
    if(this->m<10) cout << 0;
    cout << this->m << ':';
    if(this->s<10) cout << 0;
    cout << this->s << flush;//立刻显示
}

void Time::run()
{
    while(h||m||s){//设置程序结束
    sleep(1);//等待1S
    if(--s<0){
        s = 59;
        if(--m<0){
          m = 59;
          --h;
        }
    }
    Time::show();
    }
    cout << "\nTime out" << endl;
}

int main()
{
    int hour,minute,second;
    cout << "Please input countdown as \"hour minute second\" " << endl;
    cin >> hour >> minute >> second;
    Time t(hour,minute,second);
    t.run();
    return 0;
}

结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值