Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C tính tuổi từ ngày sinh

Giới thiệu

Cho ngày hiện tại và ngày sinh, tính tuổi chính xác (năm, tháng, ngày).

Ví dụ

Input: Hiện tại 21/9/2019, Sinh 25/9/1996
Output: Years: 22 Months: 11 Days: 26

Phương pháp

  • Nếu ngày sinh > ngày hiện tại: mượn ngày từ tháng trước (cộng thêm số ngày của tháng sinh), giảm tháng hiện tại 1
  • Nếu tháng sinh > tháng hiện tại: mượn 1 năm (giảm năm hiện tại 1, cộng 12 tháng)
  • Trừ từng thành phần: ngày, tháng, năm

Thuật toán

Hàm age(present_date, present_month, present_year, birth_date, birth_month, birth_year):
  month[] = {31,28,31,30,31,30,31,31,30,31,30,31}
  Nếu birth_date > present_date:
    present_date += month[birth_month-1]
    present_month--
  Nếu birth_month > present_month:
    present_year--
    present_month += 12
  final_date = present_date - birth_date
  final_month = present_month - birth_month
  final_year = present_year - birth_year
  In kết quả

Hàm main:
  Khởi tạo ngày hiện tại và ngày sinh
  Gọi age()

Code 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 += month[birth_month - 1];
        present_month--;
    }
    if (birth_month > present_month) {
        present_year--;
        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, present_month = 9, present_year = 2019;
    int birth_date = 25, birth_month = 9, birth_year = 1996;
    age(present_date, present_month, present_year, birth_date, birth_month, birth_year);
    return 0;
}

Kết quả

Present Age Years: 22 Months: 11 Days: 26

Lưu ý

Chương trình chưa xử lý năm nhuận cho tháng 2 (có thể mở rộng bằng cách kiểm tra năm nhuận khi mượn ngày).