在Python中使用//运算符除以零

问题描述

运行以下代码

p = int(input("principal: "))
interest = int(input("annual interest rate: "))
years = int(input("# of years: "))

r = interest // 100

n = years * 12

top = r * (1 + r) ** n

bottom = (1+r) ** n - 1

fraction = top // bottom

A = fraction * p
print(A)

我得到:

line 17,in <module>
    fraction = top // bottom
ZeroDivisionError: integer division or modulo by zero

我是初学者,请保持友好!

解决方法

下限除法//将结果四舍五入到最接近的整数(数据类型= 整数),而r作为整数,当{{1} }是

如果interest等于top,您会看到r会发生什么。

0fraction运算符相同。使用//对数字进行四舍五入。

round