发布一周中的一天计划

2024-03-29 09:50:43 发布

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

对于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()

Tags: orandtheforinputifisyear
1条回答
网友
1楼 · 发布于 2024-03-29 09:50:43

我不确定这是否是唯一的问题,但对于一月和二月,你有如下计算-

elif (a == 1):
    a = 11
    c = (c-1)
elif (a == 2):
    a = 12
    c = (c-1)

但是对于1900,c是0,因此您将c设置为-1。而d仍然指向19。我相信这可能是问题的根源。你知道吗

将该部分更改为以下内容后,它开始为1900一月和二月工作-

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

示例-

运行1-

Enter year: 1900
Enter month: 1
Enter day: 5
The day is Friday.

运行2-

Enter year: 1900
Enter month: 2
Enter day: 2
The day is Friday.

相关问题 更多 >