时间类Time的参考框架如下,通过重载操作符“+”实现两个时间的相加,要求将小时范围限制在023时,分钟范围限制在059分,秒钟范围限制在0~59秒。设计主程序,读入两个时间,对时间的合法性进行判断,若时间不合法,则输出“Time Error!”,若时间值合法,则进行两个时间的相加,并将结果以:“小时:分钟:秒”的格式进行输出。
class Time
{
public:
Time(int h=0,int m=0,int s=0); //构造函数
Time operator+(const Time &t); //运算符重载函数,实现两个时间的相加
void display(); //显示时间函数
private:
int hours,minutes,seconds;
};
输入格式:
共2行,每行表示一个时间,以:小时 分 秒 的格式输入 例如:10 20 45 (表示时间为10:20:45)
输出格式:
时:分钟:秒,例:21:51:30
输入样例:
在这里给出一组输入。例如:
10 20 45
11 30 45
输出样例:
在这里给出相应的输出。例如:
21:51:30
代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43#include<iostream> using namespace std; class Time { public: Time(int h=0,int m=0,int s=0) { this->hours=h; this->minutes=m; this->seconds=s; }; Time operator+(const Time &t) { int time=this->hours*3600+t.hours*3600+this->minutes*60+t.minutes*60+t.seconds+this->seconds; time=time%(3600*24); this->hours=time/3600; this->minutes=(time%3600)/60; this->seconds=(time%3600)%60; return *this; }; void display() { cout<<this->hours<<":"<<this->minutes<<":"<<this->seconds; }; private: int hours,minutes,seconds; }; int main() { int a,b,c,d,e,f; cin>>a>>b>>c>>d>>e>>f; if(a>=24 || b>=60 || c>=60 || d>=24 || e>=60 || f>=60 || a<0 || b<0 || c<0 || d<0 || e<0 || f<0) { cout<<"Time Error!"<<endl; return 0; } else{ class Time t1(a,b,c); class Time t2(d,e,f); t1=t1+t2; t1.display(); } }
最后
以上就是标致云朵最近收集整理的关于7-1 两个时间相加 (10分)的全部内容,更多相关7-1内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复