현재 날짜와 사람의 생년월일이 주어지면 현재 나이를 계산하는 작업입니다.
예시
Input-: present date-: 21/9/2019 Birth date-: 25/9/1996 Output-: Present Age Years: 22 Months:11 Days: 26
아래에 사용된 접근 방식은 다음과 같습니다. -
- 사람의 현재 날짜와 생년월일 입력
- 조건 확인
- 당월이 출생 월보다 작으면 올해가 아직 완료되지 않았기 때문에 현재 연도를 고려하지 않고 당월에 12를 더하여 월의 차이를 계산합니다.
- 현재 날짜가 생년월일보다 작으면 월을 고려하지 않고 빼기 날짜를 생성하기 위해 현재 날짜에 월 일 수를 더하면 날짜가 달라집니다.
- 이 조건이 충족되면 일, 월, 연도를 빼면 최종 결과가 나옵니다.
- 최종 연령 인쇄
알고리즘
Start
Step 1-> declare function to calculate age
void age(int present_date, int present_month, int present_year, int birth_date, int birth_month, int birth_year)
Set int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
IF (birth_date > present_date)
Set present_date = present_date + month[birth_month - 1]
Set present_month = present_month – 1
End
IF (birth_month > present_month)
Set present_year = present_year – 1
Set present_month = present_month + 12
End
Set int final_date = present_date - birth_date
Set int final_month = present_month - birth_month
Set int final_year = present_year - birth_year
Print final_year, final_month, final_date
Step 2-> In main()
Set int present_date = 21
Set int present_month = 9
Set int present_year = 2019
Set int birth_date = 25
Set int birth_month = 9
Set int birth_year = 1996
Call age(present_date, present_month, present_year, birth_date, birth_month,
birth_year)
Stop 예시
#include <stdio.h>
#include <stdlib.h>
// function to calculate current age
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("Present Age Years: %d Months: %d Days: %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;
} 출력
위의 코드를 실행하면 다음 출력이 생성됩니다.
Present Age Years: 22 Months:11 Days: 26