zoukankan      html  css  js  c++  java
  • 时间相加

    设计一个时间类,用来保存时、分、秒等私有数据成员,通过重载操作符“+”实现2个时间的相加。要求: (1)小时的时间范围限制在大于等于0;(2)分的时间范围为0~59分;(3)秒的时间范围为0~59秒。

    #include <iostream>
    using namespace std;
    class Time {
    private:
     int hours,minutes, seconds;
    public:
     Time(int h=0, int m=0, int s=0);
     Time operator + (Time &);
     void DispTime();
    };
    

    /* 请在这里填写答案 */

    int main() {
    Time tm1(8,75,50),tm2(0,6,16), tm3;
    tm3=tm1+tm2;
    tm3.DispTime();
    return 0;
    }

    输出:

    在这里给出相应的输出。例如:

    9h:22m:6s
     

    正确代码:

    void Time::DispTime(){
         cout << hours << "h:" << minutes << "m:" << seconds << "s";
     }
    Time::Time(int h,int m,int s){
        hours = h;
        minutes = m;
        seconds = s;
    
    }
    Time Time::operator+(Time &op2){
        int temp1=0;
        Time temp;
        temp.seconds = this->seconds + op2.seconds;
        if(temp.seconds>=60){
            temp.seconds %= 60;
            temp1 = 1;
            
        }
        temp.minutes = this->minutes + op2.minutes+temp1;
        temp1 = 0;
        if(temp.minutes>=60){
            temp.minutes %= 60;
            temp1 = 1;
            
        }
        temp.hours = this->hours + op2.hours+temp1;
        if(temp.hours>=24){
            temp.hours %= 24;
            
        }
        return temp;
    }
      
    
  • 相关阅读:
    hdu 1005(找循环节)
    hdu 1452(因子和+逆元)
    hdu 1215(因子和)
    hdu 1492(约数的个数)
    hdu 2136(质数筛选+整数分解)
    HDU 1286 找新朋友
    HDU 2136 Largest prime factor
    HDU 1722 Cake
    HDU 1713 相遇周期
    HDU 2138 How many prime numbers
  • 原文地址:https://www.cnblogs.com/pluie/p/12670583.html
Copyright © 2011-2022 走看看