Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

C++ Program: Tính hiệu hai khoảng thời gian (Time Difference)

Tính hiệu giữa hai mốc thời gian (giờ:phút:giây) bằng cách trừ từng thành phần, xử lý mượn (borrow) khi cần.

Thuật toán

  1. Nhập thời gian 1: h1, m1, s1
  2. Nhập thời gian 2: h2, m2, s2
  3. Nếu s2 > s1: mượn 1 phút → m1--, s1 += 60
  4. diff_sec = s1 - s2
  5. Nếu m2 > m1: mượn 1 giờ → h1--, m1 += 60
  6. diff_min = m1 - m2
  7. diff_hour = h1 - h2

Ví dụ C++

#include <iostream>
using namespace std;

struct Time {
    int hour, minute, second;
};

Time readTime(const char* label) {
    Time t;
    cout << label << " (giờ phút giây): ";
    cin >> t.hour >> t.minute >> t.second;
    return t;
}

Time diffTime(Time t1, Time t2) {
    // Giả sử t1 >= t2
    if (t2.second > t1.second) {
        t1.minute--;
        t1.second += 60;
    }
    if (t2.minute > t1.minute) {
        t1.hour--;
        t1.minute += 60;
    }
    return {t1.hour - t2.hour, t1.minute - t2.minute, t1.second - t2.second};
}

int main() {
    Time t1 = readTime("Thời gian 1");
    Time t2 = readTime("Thời gian 2");
    
    Time diff = diffTime(t1, t2);
    
    cout << "Hiệu thời gian: " 
         << diff.hour << ":" 
         << diff.minute << ":" 
         << diff.second << endl;
    return 0;
}

Kết quả mẫu

Thời gian 1 (giờ phút giây): 7 6 2
Thời gian 2 (giờ phút giây): 5 4 3
Hiệu thời gian: 2:1:59

Cải tiến: Xử lý t1 < t2 (quá nửa đêm)

Time diffTime24h(Time t1, Time t2) {
    // Chuyển về tổng giây
    int total1 = t1.hour * 3600 + t1.minute * 60 + t1.second;
    int total2 = t2.hour * 3600 + t2.minute * 60 + t2.second;
    
    int diff = total1 - total2;
    if (diff < 0) diff += 24 * 3600; // Quá nửa đêm
    
    return {diff / 3600, (diff % 3600) / 60, diff % 60};
}

C++20: std::chrono (Hiện đại, an toàn)

#include <chrono>
#include <iostream>
#include <format>

int main() {
    using namespace std::chrono;
    
    // Tạo time_of_day
    auto t1 = 7h + 6min + 2s;
    auto t2 = 5h + 4min + 3s;
    
    auto diff = t1 - t2; // duration
    
    cout << "Hiệu: " 
         << duration_cast(diff).count() << ":"
         << duration_cast(diff % hours(1)).count() << ":"
         << duration_cast(diff % minutes(1)).count() << endl;
    // Hiệu: 2:1:59
    
    return 0;
}

Lưu ý

  • Code cơ bản giả sử t1 ≥ t2 (cùng ngày)
  • Cần validate input (giờ 0-23, phút/giây 0-59)
  • C++20 <chrono> type-safe, xử lý overflow tự động
  • Thực tế: dùng std::chrono::sys_time hoặc time_point cho timestamp đầy đủ