Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลงเวลา 24 ชั่วโมงเป็น 12 ชั่วโมงใน C++

ภาพรวมปัญหา

แปลงเวลาจากรูปแบบ 24 ชั่วโมง (HH:MM:SS) เป็น 12 ชั่วโมง พร้อม AM/PM

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void convert_12hour(string str) {
    int h1 = (int)str[0] - '0';
    int h2 = (int)str[1] - '0';
    int hh = h1 * 10 + h2;
    
    string Meridien;
    if (hh < 12) Meridien = "AM";
    else Meridien = "PM";
    
    hh %= 12;
    if (hh == 0) {
        cout << "12";
        for (int i = 2; i < 8; ++i) cout << str[i];
    } else {
        cout << hh;
        for (int i = 2; i < 8; ++i) cout << str[i];
    }
    cout << " " << Meridien << '\n';
}

int main() {
    string str = "17:35:20";
    convert_12hour(str);
    return 0;
}

ผลลัพธ์ (Output)

5:35:20 PM