对于python类,我们需要创建一个程序,允许用户输入1900到2100之间的日期,它将计算一周中的某一天。
我的代码适用于除1900年1月和2月以外的所有日期,我不知道为什么。
我一直在看它太久了,我不知道什么是错的。
def main():
#Getting the main inputs from the user
year = int(input('Enter year: '))
#While loops used to check if inputs are valid
while((year > 2100) or (year < 1900)):
year = int(input('Enter year: '))
a = int(input('Enter month: '))
while((a > 12) or (a < 1)):
a = int(input('Enter month: '))
b = int(input('Enter day: '))
#check if year is a leap year
is_leap = (year % 400 == 0) or ((year % 100 !=0) and (year % 4 ==0))
#this next block checks to make sure that the day entered is valid for the month
if (a == 1) or (a == 3) or (a == 5) or (a == 7) or (a == 8) or (a == 10) or (a == 12):
while ((b < 1) or (b > 31)):
b = int(input('Enter day: '))
elif (a == 4) or (a == 6) or (a == 9) or (a == 11):
while ((b < 1) or (b > 30)):
b = int(input('Enter day: '))
else:
#this checks if the year is a leap year and whether or not the day is valid
if (a == 2) and is_leap:
while ((b < 1) or (b > 29)):
b = int(input('Enter day: '))
if (a == 2) and not is_leap:
while ((b < 1) or (b > 28)):
b = int(input('Enter day: '))
#separating the century from the year
if (year > 1999):
d = 20
elif (year < 2000):
d = 19
#slicing the year of the century off the total year
c = (year - (d *100))
#to make the algorithm work, the month number and year must be changed for certain months
if (a >= 3):
a = (a-2)
elif (a == 1):
a = 11
c = (c-1)
elif (a == 2):
a = 12
c = (c-1)
# Now for the computations
w = (13 * a-1)//5
x = c//4
y = d//4
z= w + x + y + b + c - 2 * d
r = z % 7
r = (r+7)%7
#and for the final variables and printing
if (r == 0):
day = 'Sunday.'
elif (r == 1):
day = 'Monday.'
elif (r == 2):
day = 'Tuesday.'
elif (r == 3):
day = 'Wednesday.'
elif (r == 4):
day = 'Thursday.'
elif (r == 5):
day = 'Friday.'
else:
day = 'Saturday'
print('The day is',day,)
main()
答案 0 :(得分:0)
我不确定这是否是唯一的问题,但是对于1月和2月的月份,你有一个如下的计算 -
elif (a == 1):
a = 11
c = (c-1)
elif (a == 2):
a = 12
c = (c-1)
但是对于1900
,c为0,因此您将c设置为-1
。 d
仍然指向19
。我相信这可能会导致这个问题。
将该部分更改为下面后,它开始适用于1900
jan和feb -
if (a >= 3):
a = (a-2)
elif (a == 1):
a = 11
c = (c-1)
if c == -1:
c = 99
d = d - 1
elif (a == 2):
a = 12
c = (c-1)
if c == -1:
c = 99
d = d - 1
示例 -
Run1 -
Enter year: 1900
Enter month: 1
Enter day: 5
The day is Friday.
Run2 -
Enter year: 1900
Enter month: 2
Enter day: 2
The day is Friday.