设计WyTime类

设计MyTime类
题目描述
设计一个MyTime类,成员函数SetTime()设置时间,print_12()以12(0-11)小时制显示时
间(AM上午,PM下午),print_24()以24(0-23)小时制显示时间。
输入
所需设置时间的时、分、秒(24小时制)
输出
按照12小时制和24小时制依次显示时间,注意时间格式中的冒号是英文冒号,时分秒都是两位,AM,PM前有一个空格,晚上12:00是00:00:00 AM,中午十二点是00:00:00 PM。

答案

#include <iostream>
#include <ctime>

class MyTime {
private:
    int hours;
    int minutes;
    int seconds;

public:
    void SetTime(int h, int m, int s) {
        hours = h;
        minutes = m;
        seconds = s;
    }

    void print_12() const {
        const time_t midday = 12 * 60; // 12:00 PM in 24h format
        const time_t midnight = 0;     // 12:00 AM in 24h format

        if (hours >= midday) {
            std::cout << "Time is " << hours - midday << " hours (" << (hours > midday ? "PM" : "AM") << ")" << std::endl;
        }
        else {
            std::cout << "Time is " << hours % 12 << " hours (" << (hours / 12 == 0 ? "AM" : "PM") << ")" << std::endl;
        }
    }

    void print_24() const {
        std::cout << "Time is " << hours << ":" << minutes << ":" << seconds << std::endl;
    }
};

int main() {
    int h, m, s;

    // Prompt user for time
    std::cout << "Enter the time in 24-hour format (HH:MM:SS): ";
    std::cin >> h >> m >> s;

    // Create an instance of MyTime and set the time
    MyTime myTime;
    myTime.SetTime(h, m, s);

    // Print time in 12-hour format
    myTime.print_12();

    // Print time in 24-hour format
    myTime.print_24();

    return 0;
}

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值