面向对象语言与编程,编写一个程序将24小时制的时间转换为12小时制的时间
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
int main() {
auto now = chrono::system_clock::now();
time_t now_c = chrono::system_clock::to_time_t(now);
struct tm* now_tm = localtime(&now_c);
cout << "当前时间为:" << ctime(&now_tm->tm_year + 1900) << "年" << now_tm->tm_mon + 1 << "月" << now_tm->tm_mday << "日 " << now_tm->tm_hour << ":" << now_tm->tm_min << ":" << now_tm->tm_sec << endl;
struct tm* old_tm = localtime(&now_c);
cout << "旧时间为:" << ctime(&old_tm->tm_year + 1900) << "年" << old_tm->tm_mon + 1 << "月" << old_tm->tm_mday << "日 " << old_tm->tm_hour << ":" << old_tm->tm_min << ":" << old_tm->tm_sec << endl;
return 0;
}
首先,我们可以定义一个Time类来表示时间,该类应该包含小时、分钟和秒钟三个成员变量。同时,我们也需要为该类提供一个转换函数,将24小时制时间转换为12小时制时间。
#include <iostream>
using namespace std;
class Time {
private:
int hour; // 小时数
int minute; // 分钟数
int second; // 秒数
public:
// 构造函数
Time(int h, int m, int s) : hour(h), minute(m), second(s) {}
// 将时间转换为12小时制
void convertTo12Hour() {
int newHour = hour;
string suffix = "AM";
if (hour > 12) {
suffix = "PM";
newHour = hour - 12;
}
cout << newHour << ":" << minute << ":" << second << " " << suffix << endl;
}
};
int main() {
// 创建一个Time对象表示当前时间
Time t(14, 30, 0);
// 将24小时制时间转换为12小时制时间
t.convertTo12Hour();
return 0;
}