繁体   English   中英

我收到 ZeroDivisionError,我该如何解决?

[英]I am getting a ZeroDivisionError , how do i solve this?

我是新手,我试图计算给定数字的总数,如果其中一个数字是奇数,它不会加起来就是总数,即 b

我正在做的是,如果 a / 2 没有拆分 rest 这将是偶数,那么它将添加到 b,但我得到一个 ZeroDivisionError,我做错了什么? 抱歉,如果我拼错了任何单词


for c in range(1, 7):
    a = int(input("type a number {}: ".format(c)))
    if a / 2 % 0:
        b += a

print("the sum of the numbers is equivalent to:", b)

如果您正在检查偶数,则应该是:

if a % 2 == 0:

我想你想对用户输入的偶数求和。 在这种情况下, a % 2为偶数返回 0,为奇数正整数返回 1。

  1. 请考虑使用有意义的变量名,例如“even_sum”而不是“b”。
  2. 考虑用你期望的行或代码块来评论你的代码。

修正后的代码如下。

# initialize b, which will hold the sum of the even numbers
# entered by the user.
b = 0

# prompt the user for a number 6 times.
for c in range(1, 7):
    # request a number
    a = int(input("type a number {}: ".format(c)))
    # if the number is even
    if a % 2 == 0:
        # the number is even, so add it to the running total, b
        b += a

print("The sum of the EVEN numbers is equivalent to:", b)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM