gpt4 book ai didi

Python的取模误区

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:18 24 4
gpt4 key购买 nike

我有那个代码,我不认为我真的理解模如何返回余数,不擅长数学..

代码如下:

#import the datetime class
import datetime

#declare and initialize variables
strDeadline = ""
totalNbrDays = 0
nbrWeeks = 0
nbrDays = 0

#Get Today's date
currentDate = datetime.date.today()

#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")

deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()

#Calculate number of days between the two dates
totalNbrDays = deadline - currentDate

#For extra credit calculate results in weeks & days

nbrWeeks = totalNbrDays.days / 7

#The modulo will return the remainder of the division
#which will tell us how many days are left
nbrDays = totalNbrDays.days%7

#display the result to the user

print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")

最佳答案

当您将一个整数除以另一个整数时,它并不总是均匀分布。例如,23/7 将为您提供 2 的余数,因为 23 = 7 * 3 + 2。 Modulo 为您提供除法运算的余数...23 % 7 = 2。当您的天数比一周的时间长时,这很有用。您可以使用整数除法(意味着商将是一个整数)来计算周数 23/7 = 3 然后取模来计算剩余的天数 23 % 7 = 2,告诉你 23 天等于 3 周零 2 天。

关于Python的取模误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com