大學生C++教程第九版 習題(9.7)

//頭文件
#ifndef TIME_H
#define TIME_H
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
class Time
{
public:
	Time(int,int,int);
	~Time();
	void setTime(int,int,int);
	void printStandard();
	void tick();
private:
	int hour;
	int minute;
	int second;
};
#endif

#include "Time.h"


Time::Time(int hh,int min,int sec)
{
	setTime(hh,min,sec);
}


Time::~Time()
{
}

void Time::setTime(int hh, int min, int sec)
{
	if (hh >= 0 && hh <24)
		hour = hh;
	if (min >= 0 && min < 60)
		minute = min;
	if (sec >= 0 && sec < 60)
		second = sec;
}

void Time::printStandard()
{
	cout <<setw(2)<<setfill('0')<<(( hour % 12==0 && hour>=12) ? 12:hour%12)<< ":" <<setw(2)<<setfill('0')<< minute << ":" <<setw(2)<<setfill('0')<< second << ' '
		<<((hour>=12) ? "PM":"AM")<<endl;

}

void Time::tick()
{
	if (second < 59)
		++second;
	else if (minute < 59)
	{
		++minute;
		second = 0;
	}
	else if (hour < 24)
	{
		++hour;
		minute = 0;
		second = 0;
	}
	else
	{
		hour = 0;
		minute = 0;
		second = 0;
	}


}
#include <iostream>
#include "Time.h"

int main()
{
	int i = 0;
	Time date1(11,59,59);
	date1.printStandard();

	while (i < 20)
	{
		date1.tick();
		date1.printStandard();
		i++;
	}
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章