计算时间相加--时间戳方式

仅作为记录,核心代码

int timestamp = (hours + t.hours) * 60 * 60 + (minutes+t.minutes) * 60 + (seconds + t.seconds);
int hours = timestamp / 3600 % 24;
int minutes = (timestamp % 3600) / 60;
int seconds = (timestamp % 3600) % 60;

完整代码

#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();
};

/* 请在这里填写答案 */
Time::Time(int h, int m, int s){
    hours = h;
    minutes = m;
    seconds = s; 
}
Time Time::operator + (Time &t){
    int timestamp = (hours + t.hours) * 60 * 60 + (minutes+t.minutes) * 60 + (seconds + t.seconds);
    int hours = timestamp / 3600 % 24;
    int minutes = (timestamp % 3600) / 60;
    int seconds = (timestamp % 3600) % 60;
//    cout << hours << ":" << minutes << ":" << seconds << endl;
    return Time(hours, minutes, seconds);
}
void Time::DispTime(){
    cout << hours << "h:" << minutes << "m:" << seconds << "s" << endl;
}

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

 

posted @ 2022-03-27 15:49  Naihe\  阅读(246)  评论(0)    收藏  举报
// 音乐播放器