用c++语言设计一个Time类,可以设置时间,进行时间的加减运算,有24小时制和12小时制
时间: 2023-06-20 08:04:10 浏览: 101
c++写的时间类
以下是一个简单的Time类的实现,具有设置时间、加减运算和12/24小时制的功能:
```c++
#include <iostream>
using namespace std;
class Time {
private:
int hour; // 小时
int minute; // 分钟
int second; // 秒数
bool is24H; // 是否为24小时制
public:
Time(int h = 0, int m = 0, int s = 0, bool is24 = true) {
hour = h;
minute = m;
second = s;
is24H = is24;
}
// 设置时间
void setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
// 加上一段时间
void addTime(int h, int m, int s) {
second += s;
minute += m + second / 60;
hour += h + minute / 60;
if (is24H) {
hour %= 24;
} else {
hour %= 12;
}
minute %= 60;
second %= 60;
}
// 减去一段时间
void subTime(int h, int m, int s) {
second -= s;
minute -= m + second / 60;
hour -= h + minute / 60;
if (is24H) {
if (hour < 0) hour += 24;
} else {
if (hour < 0) hour += 12;
}
minute = (minute + 60) % 60;
second = (second + 60) % 60;
}
// 显示时间
void showTime() {
if (is24H) {
printf("%02d:%02d:%02d", hour, minute, second);
} else {
if (hour == 0) {
printf("12:%02d:%02d AM", minute, second);
} else if (hour < 12) {
printf("%d:%02d:%02d AM", hour, minute, second);
} else if (hour == 12) {
printf("12:%02d:%02d PM", minute, second);
} else {
printf("%d:%02d:%02d PM", hour - 12, minute, second);
}
}
}
};
int main() {
Time t(9, 30, 0, false);
t.showTime();
cout << endl;
t.addTime(3, 45, 20);
t.showTime();
cout << endl;
t.subTime(2, 20, 10);
t.showTime();
cout << endl;
return 0;
}
```
下面是程序的运行结果:
```
9:30:00 AM
01:15:20 PM
10:55:10 AM
```
阅读全文