我想在给定日期增加天数而不使用任何库 我做了这部分代码:
Days_in_Month = [31, 27, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if isBisextile(year):
Days_in_Month[1] = 28
days = int(input("Enter number of days:\n"))
while days > 0:
if isBisextile(year):
Days_in_Month[1] = 28
date += 1
if date > int(Days_in_Month[month-1]):
month += 1
if month > 12:
year += 1
month = 1
date = 1
days -= 1
print("{}/{}/{}".format(date, month, year))
例如,如果我使用
Enter a date:
2/7/1980
Enter number of days:
1460
它产生2/7/1984而不是1/7/1984
有人知道我为什么要加一天吗?
答案 0 :(得分:1)
这似乎已解决了您的问题:
Days_in_Month[1]
应该是28或29,而不是27或28,并且每年都需要两种方式进行修正。
我写了我自己的isBisextile()
,显然它不完全符合%100或%400的所有leap年规则,但是我认为您的版本中包含了您未显示的内容我们。
year = 1980
month = 7
date = 2
Days_in_Month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isBisextile(year):
return True if year%4 == 0 else False
if isBisextile(year):
Days_in_Month[1] = 29
days = int(input("Enter number of days:\n"))
while days > 0:
if isBisextile(year):
Days_in_Month[1] = 29
else:
Days_in_Month[1] = 28
date += 1
if date > int(Days_in_Month[month-1]):
month += 1
if month > 12:
year += 1
month = 1
date = 1
days -= 1
print("{}/{}/{}".format(date, month, year))
1980年2月7日和天数:1460年达到预期的1/7/1984。