7-1 两个时间相加 (10分)

时间类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

代码

#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();
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值