微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

防止“除以零错误”的方法

如何解决防止“除以零错误”的方法

我正在运行这个:

for dataset in waycategory_values:
        if dataset['value'] in [1.0,2.0,3.0]: 
            total_highway_distance += dataset['distance']

    for dataset in waycategory_values:
        total_distance += dataset['distance']

    highway_perc = (total_highway_distance / total_distance)

    print(highway_perc)

total_distance 可能为零。是否有一种平稳的方法可以让脚本继续运行并在总距离为 0 时仅打印 0。我一直在考虑每次都将 +1 添加到 total_distance 中 - 但没有更好的方法吗?

在我看来,以下内容正在流传,但它不起作用:

if total_distance == 0:
    total_distance = 1

解决方法

它“不起作用”,因为您编写的代码没有使用您所说的逻辑。你用文字描述的内容是这样的:

# print 0 when the total distance is 0

if total_distance == 0:
    highway_perc = 0
else:
    highway_perc = total_highway_distance / total_distance

print(highway_perc)

您也可以在一行中执行此操作:

highway_perc = 0 if total_distance == 0 else total_highway_distance / total_distance

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。