C 语言计算年龄
在给定当前日期和一个人的出生日期后,我们的任务是计算他的当前年龄。
例如
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP