โจทย์
แปลงเวลาจากรูปแบบ 24 ชั่วโมง เป็นรูปแบบ 12 ชั่วโมง พร้อม AM/PM ด้วยภาษา C
วิธีแก้ปัญหา
อ่านค่าชั่วโมงและนาทีจากผู้ใช้ แล้วตรวจสอบเงื่อนไข:
- ถ้าชั่วโมง = 0 → แสดง 12:นาที AM
- ถ้าชั่วโมง < 12 → แสดง ชั่วโมง:นาที AM
- ถ้าชั่วโมง = 12 → แสดง 12:นาที PM
- อื่น ๆ → แสดง (ชั่วโมง % 12):นาที PM
อัลกอริทึม
Start:
Step 1: รับเวลาในรูปแบบ 24 ชั่วโมง
Step 2: ตรวจสอบเงื่อนไข
i. If (hour == 0) → Print 12:min AM
ii. Else if (hour < 12) → Print hour:min AM
iii. Else if (hour == 12) → Print hour:min PM
iv. Else → Print (hour % 12):min PM
Stop
โปรแกรม
#include <stdio.h>
int main() {
int hr, min;
printf("enter the time in 24 hour format: ");
scanf("%d:%d", &hr, &min);
printf("The 12 hr format time: ");
if (hr == 0) {
printf("12:%.2d AM\n", min);
} else if (hr < 12) {
printf("%d:%.2d AM\n", hr, min);
} else if (hr == 12) {
printf("%d:%.2d PM\n", hr, min);
} else {
printf("%d:%.2d PM\n", hr % 12, min);
}
return 0;
}
ผลลัพธ์
enter the time in 24 hour format: 22:37
The 12 hr format time: 10:37 PM