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

C 언어로 나이를 계산하는 프로그램 만들기


현재 날짜와 한 사람의 생년월일이 주어졌을 때, 그 사람의 현재 나이를 계산하는 것이 이번 문제의 목표입니다.

예시

입력 -: 현재 날짜 -: 21/9/2019
   생년월일 -: 25/9/1996
출력 -: 현재 나이
   년: 22 월: 11 일: 26

문제 해결에 사용된 접근 방식은 다음과 같습니다

  • 현재 날짜와 생년월일을 입력받습니다.
  • 아래 조건들을 확인합니다.
    • 현재 월이 생일 월보다 작은 경우, 올해가 아직 온전히 지나지 않았다는 의미이므로 현재 연도를 그대로 사용하지 않고, 대신 현재 월에 12를 더해 월 차이를 계산합니다.
    • 현재 일이 생일 일보다 작은 경우, 월을 그대로 사용하지 않고, 현재 일에 해당 월의 총 일수를 더한 값에서 생일 일을 빼면 일 단위의 차이를 구할 수 있습니다.
  • 위 조건 처리가 끝나면 일, 월, 년을 각각 빼서 최종 결과를 구합니다.
  • 계산된 최종 나이를 출력합니다.

알고리즘

시작
1단계 -> 나이를 계산하는 함수 선언
   void age(int present_date, int present_month, int present_year, int birth_date, int birth_month, int birth_year)
      int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } 로 설정
      IF (birth_date > present_date)
         present_date = present_date + month[birth_month - 1] 로 설정
         present_month = present_month – 1 로 설정
      End
      IF (birth_month > present_month)
         present_year = present_year – 1 로 설정
         present_month = present_month + 12 로 설정
      End
      int final_date = present_date - birth_date 로 설정
      int final_month = present_month - birth_month 로 설정
      int final_year = present_year - birth_year 로 설정
      final_year, final_month, final_date 출력
2단계 -> main() 함수에서
   int present_date = 21 로 설정
   int present_month = 9 로 설정
   int present_year = 2019 로 설정
   int birth_date = 25 로 설정
   int birth_month = 9 로 설정
   int birth_year = 1996 으로 설정
   age(present_date, present_month, present_year, birth_date, birth_month, birth_year) 호출
종료

C 코드 구현

#include <stdio.h>
#include <stdlib.h>
// 현재 나이를 계산하는 함수
void age(int present_date, int present_month, int present_year, int birth_date, int birth_month, int birth_year) {
   int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   if (birth_date > present_date) {
      present_date = present_date + month[birth_month - 1];
      present_month = present_month - 1;
   }
   if (birth_month > present_month) {
      present_year = present_year - 1;
      present_month = present_month + 12;
   }
   int final_date = present_date - birth_date;
   int final_month = present_month - birth_month;
   int final_year = present_year - birth_year;
   printf("현재 나이 - 년: %d 월: %d 일: %d", final_year, final_month, final_date);
}
int main() {
   int present_date = 21;
   int present_month = 9;
   int present_year = 2019;
   int birth_date = 25;
   int birth_month = 9;
   int birth_year = 1996;
   age(present_date, present_month, present_year, birth_date, birth_month, birth_year);
   return 0;
}

실행 결과

위 코드를 컴파일하여 실행하면 다음과 같은 출력이 생성됩니다.

현재 나이 - 년: 22 월: 11 일: 26

참고 사항

이 프로그램은 나이 계산의 기본 원리를 보여주는 예제이며, 실무에서 활용하려면 다음 사항을 고려해야 합니다.

  • 2월을 항상 28일로 가정하기 때문에 윤년(leap year)은 반영되지 않습니다.
  • 날짜가 코드에 하드코딩되어 있으므로, 실제 응용에서는 time.h 헤더의 time(), localtime() 함수를 사용해 시스템의 현재 날짜를 동적으로 가져오는 것이 좋습니다.
  • 잘못된 날짜 입력(예: 32일, 13월)에 대한 유효성 검사를 추가하면 더 견고한 프로그램이 됩니다.