python中计算年龄的程序中的一个错误

2024-03-28 09:54:00 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我写了一个简单的程序,用python计算年龄,我遇到了一个问题,结果是不正确的,我修正了它,但我想知道它的原因,我会把代码,这是一个弱代码,因为我是一个新手。你知道吗

那么,为什么我要把变量(日、月、年)放在if语句下面,而当它们放在上面时,结果是不正确的呢?谢谢你。你知道吗

CrrentYear=input("Enter the current year in numbers : ")
CurrentMonth=input("Enter the current month in numbers : ")
CurrentDay=input("Enter the current day in numbers : ")
BirthYear=input("Enter your birth year in numbers : ")
BirthMonth=input("Enter your birth month in numbers : ")
BirthDay=input("Enter your birth day in numbers : ")


if CurrentDay < BirthDay:
    CurrentDay+=30
    CurrentMonth-=1

if CurrentMonth < BirthMonth:
   CurrentMonth+=12
   CrrentYear-=1

Day=CurrentDay-BirthDay
Month=CurrentMonth-BirthMonth
Year=CrrentYear-BirthYear



print("Your age is : "+str(Year)+" "+"Years"+" "+"and"+" "+str(Month)+"     "+"Months"+" "+"and"+" "+str(Day)+" "+"Days")

Tags: theininputyourifcurrentbirthdaybirth
1条回答
网友
1楼 · 发布于 2024-03-28 09:54:00

你的问题有点模糊。。。但我会尽力帮忙的。你知道吗

我认为“up if statements”是指以上的if语句,而“down if statements”是指以下的if语句。你知道吗

如果计算DayMonthYear以上的if语句,有时代码仍然可以工作,具体取决于输入。这是因为只有当currentDay小于birthDay时,才会出现第一个if语句。你知道吗

在我的例子中,我的生日是1号,因此if语句返回False,因此结果是确定的:您不需要对日期和月份进行取整(现在)。你知道吗

但是,如果当前日期是20,而生日是10,则不能有-10天,因此必须添加一个月,然后重新计算它的天数。你知道吗

同样的逻辑也适用于月份和年份。你知道吗

相关问题 更多 >