上机内容:学习static
上机目的:学习
/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: object.cpp
* 作者:刘杰
* 完成日期: 2013年 4 月 17 日
* 版本号: v1.0
* 输入描述:无
* 问题描述:
* 程序输出:
*/
#include <iostream>
#include <cmath>
using namespace std;
class Time{
public:
Time(int h=0,int m=0,int s=0):hour(h),minute(m),sec(s){};
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;
};
void Time::show_time( )
{
char a='0',char b=' ';
if(is_24)
{
if(from0)
{
cout<<(hour<10?a:b)<<hour<<':'<<(minute<10?a:b)<<minute<<':'<<(sec<10?a:b)<<sec<<endl;
}else{
cout<<hour<<':'<<minute<<':'<<sec<<endl;
}
}else{
if(hour>=12){
hour=hour-12;
if(from0){
cout<<(hour<10?a:b)<<hour<<':'<<(minute<10?a:b)<<minute<<':'<<(sec<10?a:b)<<sec<<" "<<"pm"<<endl;
}else{
cout<<hour<<':'<<minute<<':'<<sec<<' '<<"pm"<<endl;
}
}else{
if(from0){
cout<<(hour<10?a:b)<<hour<<':'<<(minute<10?a:b)<<minute<<':'<<(sec<10?a:b)<<sec<<" "<<"am"<<endl;
}else{
cout<<hour<<":"<<minute<<":"<<sec<<" "<<"am"<<endl;
}
}
}
}
void Time::add_seconds(int n) //增加n秒钟
{
sec+=n;
if (sec>59)
{
add_minutes(sec/60);
sec%=60;
}
}
void Time::add_minutes(int n) //增加n分钟
{
minute+=n;
if (minute>59)
{
add_hours(minute/60);
minute%=60;
}
}
void Time::add_hours(int n) //增加n小时
{
hour+=n;
if (hour>23)
hour%=24;
}
void Time::change24()
{
if(is_24){
is_24=false;
}else{
is_24=true;
}
}
void Time::changefrom0()
{
//bool from0;
if(from0){
from0=false;
}else{
from0=true;
}
}
bool Time::from0=true;
bool Time::is_24=true;
int main( )
{
Time t1=Time(20,3,5);
t1.show_time( );
cout<<"切换向导为:"<<endl;
t1.changefrom0();
t1.show_time( );
cout<<"另一种:"<<endl;
t1.change24();
t1.show_time( );
int a,b,c;
cout<<"请输入需要增加时、分、秒"<<endl;
cin>>a>>b>>c;
t1.add_seconds(c);
t1.add_minutes(b);
t1.add_hours(a);
t1.show_time( );
return 0;
}
运行结果: