程序代码:
#include <iostream>
using namespace std;
class Time
{
public:
Time(int=0,int=0,int=0);
void show_time( ); //根据is_24和from0,输出适合形式-20:23:5/8:23:5 pm/08:23:05 pm
void add_seconds(int); //增加n秒钟
void add_minutes(int); //增加n分钟
void add_hours(int); //增加n小时
static void change24(); //改变静态成员is_24,在12和24时制之间转换
static void changefrom0();//改变静态成员from0,切换是否前导0
private:
static bool is_24; //为true时,24小时制,如20:23:5;为flase,12小时制,显示为8:23:5 pm
static bool from0; //为true时,前导0,8:23:5显示为08:23:05
int hour;
int minute;
int sec;
};
bool Time::is_24 = true;
bool Time::from0 = false;
//构造函数
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
sec = s;
}
//根据is_24和from0,输出适合形式-20:23:5/8:23:5 pm/08:23:05 pm
void Time::show_time( )
{
//实现24小时制和12小时制之间的切换
int h=(is_24)?hour:hour%12; //这种写法比下面注释掉的写法更简洁
//当小时为个位数时,在小时前加0
if (h<10&&from0)
{
cout<<'0';
}
cout<<h<<':';
//当分钟为个位时在分钟前加0
if(minute<10&&from0)
{
cout<<'0';
}
cout<<minute<<':';
//当秒钟为个位时,在秒钟前加0
if(sec<10 && from0)
{
cout<<'0';
}
cout<<sec;
if(!is_24)//当使用12小时制时
{
if(hour>12)
{
cout<<" pm";
}
else
{
cout<<" am";
}
}
cout<<endl;
}
void Time::add_seconds(int n)//增加n秒钟
{
sec += n;
if(sec>=60)
{
int m = sec / 60;//计算分钟
int s = sec % 60;//计算秒钟
add_minutes(m);
sec = s;
}
}
void Time::add_minutes(int n)//增加n分钟
{
minute += n;
if(minute>=60)
{
int h = minute / 60;//计算小时
int m = minute % 60;//计算分钟
add_hours(h);
minute = m;
}
}
void Time::add_hours(int n)//增加n小时
{
hour += n;
if(hour>24)
{
hour %= 24;
}
}
//24小时制和12小时制之间的切换
void Time::change24()
{
is_24 =! is_24;
}
//在十位上加不加0的切换
void Time::changefrom0()
{
from0 =! from0;
}
void main( )
{
Time t1(15,47,0);
cout<<"以24小时制显示:";
Time::changefrom0();//在个位数前加0
t1.show_time();
//切换到12小时制
Time::change24();
cout<<"以12小时制显示:";
t1.show_time();
//增加20秒
t1.add_seconds(20);
//切换到24小时制
Time::change24();
cout<<"以24小时制显示增加20秒后的时间:";
Time::changefrom0();//在个位数前加0
t1.show_time();
//切换到12小时制
Time::change24();
cout<<"以12小时制显示增加20秒后的时间:";
t1.show_time();
//增加20分钟
t1.add_minutes(20);
//切换到24小时制
Time::change24();
cout<<"以24小时制显示增加20分钟后的时间:";
Time::changefrom0();//在个位数前加0
t1.show_time();
//切换到12小时制
Time::change24();
cout<<"以12小时制显示增加20分钟后的时间:";
t1.show_time();
//增加20小时
t1.add_hours(20);
//切换到24小时制
Time::change24();
cout<<"以24小时制显示增加20小时后的时间:";
t1.show_time();
//切换到12小时制
Time::change24();
cout<<"以12小时制显示增加20小时后的时间:";
t1.show_time();
system("pause");
}
执行结果: