第五週 專案3-時間類(2)
阿新 • • 發佈:2019-01-29
/* *Copyright(c)2014,煙臺大學計算機與控制工程學院 *Allrights reserved. *檔名稱:test.cpp *作者:肖雪 *完成日期:2016年4月12日 *版本號:v1.0 * *問題描述: (2)再增加三個成員函式,要求在類內宣告,類外定義。 * add_seconds(int) //增加n秒鐘 * add_minutes(int) //增加n分鐘 * add_hours(int) //增加n小時 */ #include<iostream> using namespace std; class Time { public: void set_time( ); void show_time( ); void add_seconds(int); void add_minutes(int); void add_hours(int); private: bool is_time(int, int, int); int hour; int minute; int sec; }; void Time::set_time( ) { char c1,c2; cout<<"請輸入時間(格式hh:mm:ss)"; while(1) { cin>>hour>>c1>>minute>>c2>>sec; if(c1!=':'||c2!=':') cout<<"格式不正確重輸"<<endl; else if (!is_time(hour,minute,sec)) cout<<"時間非法,請重新輸入"<<endl; else break; } } void Time::show_time( ) { cout<<hour<<":"<<minute<<":"<<sec<<endl; } bool Time::is_time(int h,int m, int s) { if (h<0 ||h>24 || m<0 ||m>60 || s<0 ||s>60) return false; else return true; } void Time::add_seconds(int n) { sec+=n; if(sec>=60) { minute+=sec/60; sec=sec%60; } } void Time::add_minutes(int n) { minute+=n; if(minute>=60) { hour+=minute/60; minute=minute%60; } } void Time::add_hours(int n) { hour+=n; if(hour>24) { hour=hour-24; } } int main( ) { Time t1; int n; t1.set_time( ); cout<<"請輸入要增加的時間秒數"<<endl; cin>>n; t1.add_seconds(n); t1.add_minutes(n); t1.add_hours(n); t1.show_time( ); return 0; }