計算一個人從出生到現在活了多少天


要求:給出一個人的出生日期,計算出該人到今天已經活過的天數,出生的那一天算一天,現在這一刻也算一天

思路:假定這個人是19900324現在時間為20140310

1.計算1990年到2014年這24年中的天數 days = (2014 - 1990) * 365,每一年按平年算

2.計算1990年到2014年有有n個閏年 days = days + n

3.計算0324到0310的天數temp_days days = days + temp_days

 

這中間還有一些細節需要考慮,下面是用python實習的代碼,試了兩個日期沒怎么調試

Caculate.py

 1 import datetime
 2 import pdb
 3 
 4 #定義計算一個人從出生到現在活的天數類
 5 class Caculate:
 6     #每個月天數 2月算的28天
 7     __monthDaysArray = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 8     __days = 0
 9 
10      #定義計算函數
11     def caculateDays(self):
12         #獲取用戶的出生日期
13         bir_date = input("請輸入你的出生日期,格式為19900806")
14         bir_year = int(bir_date[0:4])
15         bir_month = int(bir_date[4:6])
16         bir_day = int(bir_date[6:8])
17         #獲取當前系統年月日
18         now =datetime.datetime.now()
19         cur_year = now.year
20         cur_month = now.month
21         cur_day = now.day
22         #計算如19900806-20140806之間的天數
23         self.__days = (cur_year - bir_year) * 365
24         #計算1990-2014之間閏年次數 出生月份小月2月從1990年開始計算
25         if bir_month < 2:
26             for tempYear in range(bir_year, cur_year - 1, 1):
27                 if self.isReap(tempYear):
28                     self.__days += 1
29         else:
30             for tempYear in range(bir_year + 1, cur_year, 1):
31                 if self.isReap(tempYear):
32                     self.__days += 1
33         temp_days = 0
34         if cur_month < bir_month:
35             temp_days = self.__monthDaysArray[cur_month] - cur_day
36             for temp_month in range(cur_month + 1, bir_month, 1):
37                 temp_days += self.__monthDaysArray[temp_month]
38             if cur_month <= 2 and bir_month > 2:
39                 if self.isReap(cur_year):
40                     temp_days += 1
41             self.__days -= temp_days
42         if cur_month > bir_month:
43             self.__days += temp_days
44         self.__days += 1
45 
46         return  self.__days
47 
48     #判斷是否為閏年
49     def isReap(self, year):
50         if year % 100 == 0 and year % 4 == 0:
51             return True
52         elif year % 100 != 0 and year % 4 == 0:
53             return True
54         else:
55             return False

mainF.py

 1 import Caculate
 2 #測試類
 3 def main():
 4     caculate = Caculate.Caculate()
 5     days = caculate.caculateDays()
 6     print("你已經活了", days)
 7 
 8 
 9 if __name__ == '__main__':
10     main()

中間還有很多異常沒有處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM