【问题标题】:Division by zero using // operator in python在python中使用//运算符除以零
【发布时间】:2020-09-04 13:56:47
【问题描述】:

运行以下代码:

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

我是初学者,请善待!

【问题讨论】:

  • “ZeroDivisionError:整数除法或模除以零”。正如错误所说,bottom 为 0。请检查其余数据以了解原因。

标签: python calculator


【解决方案1】:

地板除法// 将结果向下舍入到最接近的整数(数据类型 = 整数),rinterest.

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

fraction// 运算符也是如此。使用round 对数字进行四舍五入。

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 = round(fraction * p, 2)
print(A)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2015-02-01
    • 2016-09-09
    • 2011-04-15
    • 2022-11-24
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多