为什么模数%不起作用?

时间:2017-11-03 04:41:41

标签: python modulus

我正在创建一个程序,使用年龄来确定年费等因素,并计算我使用模数运算符(%)的年费。由于某种原因,整数%1不创建0。 为什么这样做,我该如何解决? 我的预期输出是每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 个答案:

答案 0 :(得分:0)

主要问题是你增加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)))