第七週--專案1-靜態成員應用
阿新 • • 發佈:2019-02-14
/* * Copyright (c) 2011, 煙臺大學計算機學院 * All rights reserved. * 作 者:王靜 * 完成日期:2013 年 4 月 16 日 * 版 本 號:v1.0 * 輸入描述: * 問題描述: 設計含有靜態資料成員和成員函式的Time類:靜態資料 成員類中所有的物件共有的資料 * 程式輸出: * 問題分析: * 演算法設計:略 */ #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 a) { int s,m,h; sec+=a; if(sec>60){ s=sec%60; m=sec/60; minute=minute+m; if(minute>60){ m=minute%60; h=minute/60; hour=hour+h; if(hour>24){ hour=h%24;} }minute=m; } sec=s; } void Time::add_minutes(int b) { int m,h; minute=minute+b; if(minute>60){ m=minute%60; h=minute/60; hour=hour+h; if(hour>24){ h=h%24;} } minute=m; } void Time::add_hours(int c) { hour=hour+c; if(hour>24){ for(;hour>24;) hour=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,34,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=Time(20,34,5); t1.add_seconds(c); //增加n秒鐘 t1.add_minutes(b); //增加n分鐘 t1.add_hours(a); //增加n小時 t1.show_time( ); return 0; }
執行結果:
(貼圖)
心得體會: