本文所述为C++实现闹钟程序的方法,代码结构相对简单,注释也较为完善。现分享给大家供大家参考。
具体功能代码如下:
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//时间类
class Time{
private:
int hour;
int minute;
int second;
public:
//设置时间
void set(int h,int m,int s){
hour = h;
minute = m;
second = s;
}
//时间走一秒,时分秒的变化情况
void next(){
if(second<59)
second++;
else if(minute<59){
second=0;
minute++;}
else if(hour<23){
minute=0;
hour++;}
else
hour=0;
}
//得到时间
int get(){
return hour*10000+minute*100+second;
}
};
//时钟类
class Clock{
private:
Time now;
Time ring_time;
public:
//对表,设定初始时间
void adjust_now(int h,int m,int s){
now.set(h,m,s);
cout<<"现在的时间是:"<<h<<"时"<<m<<"分"<<s<<"秒"<<endl;
}
//设定闹铃时间
void adjust_ring(int h,int m,int s){
ring_time.set(h,m,s);
cout<<"闹铃时间是:"<<h<<"时"<<m<<"分"<<s<<"秒"<<endl;
}
//时间过一秒
void tick(){
long int old=time(0);
while(time(0)==old)
;
now.next();
}
//显示当前时间
void showtime(){
cout<<now.get()<<endl;
}
//时钟开始走时,等到了闹铃时间,开始响
void run(){
do{
tick();
showtime();
if(now.get()>=ring_time.get())
cout<<'\a';
}while(1);
}
};
int main(){
Clock c;
c.adjust_now(18,35,40); //起始时间
c.adjust_ring(18,35,45); //闹铃时间
c.run();
}
|
感兴趣的读者可以测试运行一下该实例代码,功能不足之处可以根据情况加以改进和完善。希望该实例能够对大家学习C++起到一定的帮助作用。








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。