ปัญหา
ให้สองช่วงเวลาในรูปแบบ String 'HH:MM:SS' โดย HH = ชั่วโมง MM = นาที SS = วินาที ต้องหาความต่างในรูปแบบเดียวกัน
Time period 1 = 8:6:2 Time period 2 = 3:9:3 Time Difference = 4:56:59
หลักการคำนวณ
- แปลงเวลาทั้งสองเป็นวินาทีทั้งหมด
- หาความต่าง (ลบเวลาที่น้อยกว่าออกจากมากกว่า)
- แปลงกลับเป็น ชั่วโมง:นาที:วินาที
ตัวอย่างโค้ด C++ (แบบคำนวณทีละหน่วย)
#include <iostream>
using namespace std;
int main() {
int hour1, minute1, second1;
int hour2, minute2, second2;
int diff_hour, diff_minute, diff_second;
cout << "Enter time period 1\n";
cout << "Enter hours, minutes and seconds respectively: " << endl;
cin >> hour1 >> minute1 >> second1;
cout << "Enter time period 2\n";
cout << "Enter hours, minutes and seconds respectively: " << endl;
cin >> hour2 >> minute2 >> second2;
// จัดการการยืม (Borrow) จากหน่วยใหญ่
if (second2 > second1) {
minute1--;
second1 += 60;
}
diff_second = second1 - second2;
if (minute2 > minute1) {
hour1--;
minute1 += 60;
}
diff_minute = minute1 - minute2;
diff_hour = hour1 - hour2;
cout << "Time Difference is " << diff_hour << ":"
<< diff_minute << ":" << diff_second;
return 0;
}
ผลลัพธ์ตัวอย่าง
Enter time period 1 Enter hours, minutes and seconds respectively: 7 6 2 Enter time period 2 Enter hours, minutes and seconds respectively: 5 4 3 Time Difference is 2:1:59
วิธีแปลงเป็นวินาที (Alternative - แนะนำ)
int toSeconds(int h, int m, int s) {
return h * 3600 + m * 60 + s;
}
void fromSeconds(int total, int &h, int &m, int &s) {
h = total / 3600;
total %= 3600;
m = total / 60;
s = total % 60;
}
// ใช้งาน:
int t1 = toSeconds(hour1, minute1, second1);
int t2 = toSeconds(hour2, minute2, second2);
int diff = abs(t1 - t2);
fromSeconds(diff, diff_hour, diff_minute, diff_second);
ข้อดีของวิธีแปลงวินาที
- รองรับเวลาข้ามวันได้ (ถ้าเกิน 24 ชม.)
- โค้ดสั้น กำลังใจความผิดพลาดน้อยกว่า
จัดการ Borrow อัตโนมัติ ไม่ต้องเขียน Logic เอง