C++秒表功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++秒表功能

被迫敲代码的张先森   2022-06-19 我要评论

抽象出CLOCK类来制作一个电子秒表,能够自动跳转

代码中有些陌生的库函数,顺便介绍一下:

1.system(“cls”)函数

system函数代表执行系统命令,system(“cls”)就是执行命令”清屏“的意思。

#include <windows.h>
system("cls");  

2.setw()与setfill()函数

在C++中,setw(int n)用来控制输出间隔。setw()默认填充的内容为空格,可以setfill()配合使用设置其他字符填充。注意:setw和setfill 被称为输出控制符,使用时需要在程序开头写上#include “iomanip.h”,否则无法使用。

3.Sleep()函数

功 能: 执行挂起一段时间
用 法: unsigned sleep(unsigned n);//n为毫秒
使用时带上头文件#include <windows.h>

整个程序代码如下:

#include<iostream>
#include<iomanip>
#include <windows.h>
using  namespace  std;
class CLOCK
{
private:
    int hour;
    int minute;
    int second;
public:
    CLOCK(int newh=0,int newm=0, int news=0);
    ~CLOCK();
    void init(int newh,int newm, int news);
    void run();
};

CLOCK::CLOCK(int newh,int newm, int news)
{
    hour=newh;
    minute=newm;
    second=news;
}
void CLOCK::init(int newh,int newm, int news)
{
    hour=newh;
    minute=newm;
    second=news;
}
void CLOCK::run()
{
    while(1)
    {
        system("cls");
        cout<<setw(2)<<setfill('0')<<hour<<":";
        cout<<setw(2)<<setfill('0')<<minute<<":";
        cout<<setw(2)<<setfill('0')<<second;
        Sleep(1000);
        if(++second==60)
        {
            second=0;
            minute=minute+1;
            if(minute==60)
            {
                minute=0;
                hour=hour+1;
                if(hour==24)
                {
                    hour=0;
                }
            }
        }
    }
}
CLOCK::~CLOCK()
{
}
int main()
{
    CLOCK c;
    c.init(23,59,55);
    c.run();
    system("pause");
    return 0;

}

代码执行如下

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们