一、问题及代码
#include<iostream.h>
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 a); //增加n秒钟
void add_minutes(int b); //增加n分钟
void add_hours(int c); //增加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;
};
//下面写出静态成员的初始化及各成员函数的定义……
int main( )
{
Time t1(23,14,25),t2(8,45,6);
cout << "24时制, 不前导0:" << endl;
cout << " t1是:";
t1.show_time();
cout << " t2是:";
t2.show_time();
t1.add_hours(10);
t2.add_hours(10);
Time::changefrom0();
cout << "10小时后, 切换是否前导0:" << endl;
cout << " t1是:";
t1.show_time();
cout << " t2是:";
t2.show_time();
Time::change24();
cout << "换一种制式" << endl;
cout << " t1是:";
t1.show_time();
cout << " t2是:";
t2.show_time();
return 0;
}
Time::Time(int h, int m, int s)
{
hour = h, minute = m, sec = s;
}
bool Time::is_24 = true;
bool Time::from0 = true;
void Time::show_time()
{
if (is_24)
{
if (from0)
{
cout << (hour<10? "0":"") << hour <<":"<< (minute < 10 ? "0":"") << minute << ':' << (sec < 10 ? "0":"") << sec << endl;
}
else
{
cout << hour << ':' << minute << ':' << sec << endl;
}
}
else
{
if (from0)
{
cout << (hour < 10||(hour - 12 >=0 && hour - 12 < 10) ? "0":"") << (hour > 12 ? hour-12 : hour) << ':' << (minute < 10 ? "0":"") << minute << ':' << (sec < 10 ? "0":"") << sec << ' ' << (hour > 11 ? "pm" : "am") << endl;
}
else
{
cout <<(hour>12?hour-12:hour)<<':'<<minute<<':'<<sec<<' '<<(hour>11?"pm":"am") <<endl;
}
}
}
void Time::add_seconds(int a)
{
int k,l;
k=a/60;
l=a%60;
sec=sec+l;
minute=minute+k;
if(sec>=60)
minute=minute+1;
if(minute>=60)
hour=hour+1;
if(hour>=24)
hour=0;
}
void Time::add_minutes(int b)
{
int d,q;
d=b/60;
q=b%60;
minute=minute+q;
hour=hour+d;
if(minute>=60)
hour=hour+1;
if(hour>=24)
hour=hour-24;
}
void Time::add_hours(int c)
{
int v;
v=c%24;
hour=hour+v;
if(hour>=24)
hour=hour-24;
}
void Time::change24()
{
is_24=!is_24;
if(is_24)
cout<<"已换成24制"<<endl;
else
cout<<"已换成12制"<<endl;
}
void Time::changefrom0()
{
from0 = !from0;
if (from0) cout << "已切换为前导0输出。" << endl;
else cout << "已切换为非前导0输出。" << endl;
}
二、 运行结果:
三、心得体会:
第二个C++程序,有很多错误,这些都只能通过实践来慢慢改正,所以应该多多练习。
C++,我会好好学的!
、知识点总结:
类函数和成员函数,调用要分清。选择判断要更熟悉。
对博文提交的程序书写规范很重要,最起码的要求:(1)缩格排版;(2)一句一行;(3)花括号位置;(4)适度的注释。