21xrx.com
2025-04-12 06:46:19 Saturday
文章检索 我的文章 写文章
C++实现两个时间相加
2023-07-02 21:37:06 深夜i     10     0
C++ 时间 相加

C++是一种广泛使用的编程语言,该语言拥有强大的功能和灵活性,可以用于实现各种应用程序和算法。其中,时间加法是一个常见的问题,可以通过使用C++来实现。

实现两个时间相加的方法主要有两种。第一种方法是将两个时间转换为秒数,然后将它们相加,最后将结果转换为时间格式。这种方法比较直接而且简单,代码如下:

#include<iostream>
using namespace std;
class Time {
  int hours, minutes, seconds;
public:
  Time() : hours(0), minutes(0), seconds(0) {}
  Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
  void display()
    cout << "Time = " << hours << ":" << minutes << ":" << seconds << endl;
  
  Time operator+(Time const &obj) {
    Time res;
    int set = 0;
    res.seconds = seconds + obj.seconds;
    if (res.seconds > 59)
      res.seconds -= 60;
      set = 1;
    
    res.minutes = set + minutes + obj.minutes;
    set = 0;
    if (res.minutes > 59)
      res.minutes -= 60;
      set = 1;
    
    res.hours = set + hours + obj.hours;
    return res;
  }
};
int main() {
  Time t1(5, 19, 45), t2(9, 48, 20), t3;
  t3 = t1 + t2;
  t3.display();
  return 0;
}

第二种方法是使用C++的时间库来实现。在这种方法中,我们可以使用C++的time.h头文件中的time_t和tm数据类型来表示时间,并使用C++的mktime函数来将两个时间相加。代码如下:

#include<iostream>
#include<ctime>
using namespace std;
class Time {
  time_t rawtime;
  struct tm * timeinfo;
  int hours, minutes, seconds;
public:
  Time() : hours(0), minutes(0), seconds(0) {
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    hours = timeinfo->tm_hour;
    minutes = timeinfo->tm_min;
    seconds = timeinfo->tm_sec;
  }
  Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
  void display()
    cout << "Time = " << hours << ":" << minutes << ":" << seconds << endl;
  
  Time operator+(Time const &obj) {
    Time res;
    res.seconds = (seconds + obj.seconds) % 60;
    res.minutes = ((seconds + obj.seconds) / 60 + minutes + obj.minutes) % 60;
    res.hours = ((seconds + obj.seconds) / 60 + minutes + obj.minutes) / 60 + hours + obj.hours;
    return res;
  }
};
int main() {
  Time t1(5, 19, 45), t2(9, 48, 20), t3;
  t3 = t1 + t2;
  t3.display();
  return 0;
}

以上是C++实现两个时间相加的两种方法,其中第一种方法适用于简单的应用程序,而第二种方法则适合需要对时间进行更复杂操作的应用程序。通过这些代码,我们可以更好地理解C++的使用方法和程序实现原理,并可以在日常编程中使用这些技巧提高自己的编程能力。

  
  

评论区