Trong ví dụ này, bạn sẽ học cách tính toán sự khác biệt giữa hai khoảng thời gian bằng cách sử dụng một hàm do người dùng xác định.
Để hiểu ví dụ này, bạn nên có kiến thức về các chủ đề lập trình C sau:
- C Các chức năng do người dùng định nghĩa
- C struct
- C Cấu trúc và Chức năng
- C cấu trúc và con trỏ
Tính toán sự khác biệt giữa hai khoảng thời gian
#include struct TIME ( int seconds; int minutes; int hours; ); void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff); int main() ( struct TIME startTime, stopTime, diff; printf("Enter the start time. "); printf("Enter hours, minutes and seconds: "); scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds); printf("Enter the stop time. "); printf("Enter hours, minutes and seconds: "); scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds); // Difference between start and stop time differenceBetweenTimePeriod(startTime, stopTime, &diff); printf("Time Difference: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds); printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds); printf("= %d:%d:%d", diff.hours, diff.minutes, diff.seconds); return 0; ) // Computes difference between time periods void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff) ( while (stop.seconds> start.seconds) ( --start.minutes; start.seconds += 60; ) diff->seconds = start.seconds - stop.seconds; while (stop.minutes> start.minutes) ( --start.hours; start.minutes += 60; ) diff->minutes = start.minutes - stop.minutes; diff->hours = start.hours - stop.hours; )
Đầu ra
Nhập thời gian bắt đầu. Nhập giờ, phút và giây: 13 34 55 Nhập thời gian dừng. Nhập giờ, phút và giây: 8 12 15 Chênh lệch thời gian: 13:34:55 - 8:12:15 = 5:22:40
Trong chương trình này, người dùng được yêu cầu nhập hai khoảng thời gian và hai khoảng thời gian này được lưu trữ trong các biến cấu trúc startTime và stopTime tương ứng.
Sau đó, hàm differenceBetweenTimePeriod()
tính toán sự khác biệt giữa các khoảng thời gian. Kết quả được hiển thị từ main()
hàm mà không cần trả lại nó (sử dụng lệnh gọi bằng kỹ thuật tham chiếu ).