Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C언어로 시작 시간과 종료 시간의 차이를 계산하는 프로그램

시, 분, 초 단위로 시작 시간과 종료 시간을 입력받은 뒤, 두 시간 사이의 차이를 구하는 것이 이 프로그램의 목표입니다.

시간 차이를 계산할 때 핵심이 되는 것은 자리내림(빌려오기) 처리입니다. 예를 들어 초 단위에서 빼야 할 값이 더 크다면 분에서 1을 빌려와 초에 60을 더해 계산해야 하며, 분 단위도 마찬가지 방식으로 처리합니다.

시간 차이 계산 로직

시작 시간과 종료 시간의 차이를 구하는 기본적인 논리는 다음과 같습니다.

while (stop.sec > start.sec){
    --start.min;
    start.sec += 60;
}
diff->sec = start.sec - stop.sec;
while (stop.min > start.min) {
    --start.hrs;
    start.min += 60;
}
diff->min = start.min - stop.min;
diff->hrs = start.hrs - stop.hrs;

예제 프로그램

다음은 구조체(struct)를 활용하여 시작 시간과 종료 시간의 차이를 구하는 완전한 C 프로그램입니다.

#include <stdio.h>
struct time {
    int sec;
    int min;
    int hrs;
};
void diff_between_time(struct time t1,
struct time t2,
struct time *diff);
int main(){
    struct time start_time, stop_time, diff;
    printf("Enter start time. \n");
    printf("Enter hours, minutes and seconds: ");
    scanf("%d %d %d", &start_time.hrs,
    &start_time.min,
    &start_time.sec);
    printf("Enter the stop time. \n");
    printf("Enter hours, minutes and seconds: ");
    scanf("%d %d %d", &stop_time.hrs,
    &stop_time.min,
    &stop_time.sec);
    // 시작 시간과 종료 시간의 차이 계산
    diff_between_time(start_time, stop_time, &diff);
    printf("\ntime Diff: %d:%d:%d - ", start_time.hrs,
    start_time.min,
    start_time.sec);
    printf("%d:%d:%d ", stop_time.hrs,
    stop_time.min,
    stop_time.sec);
    printf("= %d:%d:%d\n", diff.hrs,
    diff.min,
    diff.sec);
    return 0;
}
// 두 시간 구간의 차이를 계산하는 함수
void diff_between_time(struct time start,
struct time stop,
struct time *diff){
    while (stop.sec > start.sec) {
        --start.min;
        start.sec += 60;
    }
    diff->sec = start.sec - stop.sec;
    while (stop.min > start.min) {
        --start.hrs;
        start.min += 60;
    }
    diff->min = start.min - stop.min;
    diff->hrs = start.hrs - stop.hrs;
}

실행 결과

위 프로그램을 컴파일하여 실행하면 다음과 같은 결과가 출력됩니다.

Enter start time.
Enter hours, minutes and seconds: 12 45 57
Enter the stop time.
Enter hours, minutes and seconds: 20 35 20
time Diff: 12:45:57 - 20:35:20 = -8:10:37

코드 설명

프로그램의 동작 흐름을 정리하면 다음과 같습니다.

1. 구조체 정의: struct time은 시(hrs), 분(min), 초(sec) 세 개의 정수 멤버를 가지며, 하나의 시각 정보를 표현합니다.

2. 입력 처리: main() 함수에서 시작 시간과 종료 시간을 각각 시, 분, 초 형태로 사용자에게 입력받습니다.

3. 차이 계산: diff_between_time() 함수는 포인터(struct time *diff)를 통해 결과를 전달합니다. 초 단위 비교 후 부족하면 분에서 1을 빌려오고, 마찬가지로 분 단위가 부족하면 시간에서 1을 빌려와 뺄셈을 수행합니다.

4. 결과 출력: 계산된 차이를 '시:분:초' 형식으로 화면에 출력합니다.

참고로 위 실행 예시에서는 종료 시간이 시작 시간보다 늦기 때문에 음수(-8:10:37)가 출력됩니다. 실제 경과 시간을 구하려면 더 늦은 시간을 시작 시간으로 입력하거나, 절댓값 처리 등 추가 로직을 적용하는 것이 좋습니다.