簡體   English   中英

在python中計算年齡的程序中的錯誤

[英]An error in a program to calculate age in 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")

你的問題有點含糊......但我會盡力提供幫助。

我認為“向上 if 語句”是指在if語句之上,“向下 if 語句”是指在if語句之下

如果您在if語句上方計算DayMonthYear ,有時代碼仍然可以工作,具體取決於輸入。 這是因為您的第一個if語句僅在currentDay小於birthDay

就我而言,我的生日是 1 號,因此if語句返回False ,所以結果沒問題:您不需要舍入日期和月份(還)。

但是,如果當前日期是20並且生日是10 ,則不能有-10天,因此您必須添加一個月,並重新計算它是多少天。

同樣的邏輯適用於月份和年份。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM