为什么模数 % 不起作用?

Why is modulus % not working?

我正在创建一个程序,该程序使用年龄来确定年费等因素,并使用模数运算符 (%) 来计算年费。由于某种原因,整数 % 1 不会创建 0。 为什么要这样做,我该如何解决? 我的预期输出是 "year" 每 12 次迭代打印一次。

age=int(input("Age"))
quit=""
while quit!="quit":
    print(age%1)
    if age%1==0 or age%1==1:
        print("Year.")
    quit=input("Type quit to quit")
    age+=1/12

主要问题是您递增了 1/12,计算得出浮点数等于 0.08333333333333333。我建议你用几个月而不是几年来工作

years = int(input("Age (years): "))
months = years * 12

# Don't use built-in quit
quit_message = ""
while quit_message != "quit":
    if months % 12 == 0:
        print("Year.")
    quit_message = input("Type quit to quit: ")
    months += 1

# I suppose you need an age in the end
print('{} year(s) {} month(s).'.format(*divmod(months, 12)))