输入一个学生的生日和当前日期,求实际年龄
时间: 2023-05-11 15:03:09 浏览: 58
您好,可以使用 Python 编写一个函数来计算实际年龄,代码如下:
```python
from datetime import datetime
def calculate_age(birth_date, current_date):
birth_date = datetime.strptime(birth_date, '%Y-%m-%d')
current_date = datetime.strptime(current_date, '%Y-%m-%d')
age = current_date.year - birth_date.year - ((current_date.month, current_date.day) < (birth_date.month, birth_date.day))
return age
```
其中,birth_date 和 current_date 都是字符串类型,格式为 '%Y-%m-%d',例如 '2000-01-01'。调用该函数,传入学生的生日和当前日期,即可计算出实际年龄。
相关问题
使用Python,输入一个学生的生日和当前日期,输出该学生的实际年龄
好的,我可以帮你写一个Python程序来实现这个功能。你需要提供学生的生日和当前日期,以便计算实际年龄。以下是代码示例:
```python
from datetime import date
def calculate_age(birthdate, current_date):
"""
计算一个人的实际年龄
:param birthdate: 生日,格式为 (年, 月, 日)
:param current_date: 当前日期,格式为 (年, 月, 日)
:return: 年龄
"""
birth_year, birth_month, birth_day = birthdate
current_year, current_month, current_day = current_date
age = current_year - birth_year
if (current_month, current_day) < (birth_month, birth_day):
age -= 1
return age
# 测试代码
birthdate = (2000, 1, 1)
today = date.today()
current_date = (today.year, today.month, today.day)
age = calculate_age(birthdate, current_date)
print(f"该学生的实际年龄是 {age} 岁")
```
你只需要将上面的代码粘贴到Python文件中并运行,然后输入学生的生日和当前日期即可获得该学生的实际年龄。
用c语言,输入一个学生的生日和当前日期,输出该学生的实际年龄
您好,根据您的要求,我是CSDN开发的C知道,一个AI语言模型,我将回答您的问题。
以下是使用C语言编写的代码,用于计算学生的实际年龄:
```
#include <stdio.h>
int main()
{
int birth_year, birth_month, birth_day;
int current_year, current_month, current_day;
int age;
// 读取学生的生日
printf("请输入学生的生日(年 月 日,以空格分隔):");
scanf("%d %d %d", &birth_year, &birth_month, &birth_day);
// 读取当前日期
printf("请输入当前日期(年 月 日,以空格分隔):");
scanf("%d %d %d", ¤t_year, ¤t_month, ¤t_day);
// 计算年龄
age = current_year - birth_year;
if (current_month < birth_month ||
(current_month == birth_month && current_day < birth_day)) {
age--;
}
// 输出结果
printf("该学生的实际年龄为:%d岁\n", age);
return 0;
}
```
以上代码首先读取学生的生日和当前日期,然后计算出学生的实际年龄,并将结果输出。如果您有任何疑问,请随时问我。