奇怪的错误:ZeroDivisionError:浮点除以零

时间:2018-11-02 18:20:11

标签: python python-3.x math

我发现了一种奇怪的行为,希望有人对此做出解释。我在做:

if len(list) > 1 and len(list2) > 1:
   total = sum(list) + sum(list2)
   result = percentage(sum(list), total)

def percentage(part, whole):
    return float(part) / float(whole) *100

这两个列表是float和int值的混合。我偶尔会得到:

  

ZeroDivisionError:浮点数被零除

这对我来说没有意义。有人知道发生了什么吗?

2 个答案:

答案 0 :(得分:3)

如果打印出导致发生此错误的@SpringBootApplication public class MainApp{ public static void main(String[] args) { SpringApplication.run(MainApp.class, args); } } part的值,则问题很明显。

解决方案是像这样处理任何零除错误

whole

或者,您可以在除法之前检查零

       try:
           result = percentage(sum(list), total)
       except ZeroDivisionError:
           # Handle the error in whatever way makes sense for your application

(感谢Joran Beasley和Max在数学上做到这一点正确)

答案 1 :(得分:0)

使用try / exception:

const { a, b } = { a: 'Letter A', b: 'Letter B' };

这不会由于错误而退出程序,只会显示错误。