python整数除法错误 - 以零为模 - 但除数!= 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14578790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:52:41  来源:igfitidea点击:

python integer division error - modulo by zero - BUT divisor != 0

pythondivisionmodulo

提问by ccdpowell

I am new to doing simple math using python, so sorry if this is a silly question.

我是使用 python 做简单数学的新手,如果这是一个愚蠢的问题,很抱歉。

I have 8 variables that are all set to integers and these integers are used when performing a simple calculation.

我有 8 个变量都设置为整数,并且在执行简单计算时使用这些整数。

a = 0
b = 17
c = 152
d = 1
e = 133
f = 19
g = 20
h = 0

answer = ( ( ( a / f ) + b + c ) - ( g + ( h / f ) ) ) / ( d / f )

print answer

When I run this code, I get the error, ZeroDivisionError: integer division or modulo by zero.

当我运行此代码时,出现错误 ZeroDivisionError: integer Division or modulo by zero。

I have read about this error and all documentation points towards my divisor being zero, but if I print this with the numbers as strings in place of the variables, I get:

我已经阅读了有关此错误的所有文档,并且所有文档都指出我的除数为零,但是如果我使用数字作为字符串代替变量来打印它,我会得到:

( ( ( 0 / 19 ) + 17 + 152 ) - ( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )

Nowhere in this statement is the divisor zero.

该语句中没有除数零。

Please let me know how I need to change my expression in order to get the answer 2831. Note that I can change the type of the variables to a float or other. Thank you for your help!

请让我知道我需要如何更改表达式才能获得答案 2831。请注意,我可以将变量的类型更改为浮点数或其他类型。感谢您的帮助!

采纳答案by Rohit Jain

Probably you are using Python 2.x, where x / yis an integer division.

也许你正在使用Python 2.x,其中x / y的一个integer division

So, in the below code: -

所以,在下面的代码中: -

( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )

1 / 19is an integer division, which results in 0. So the expression is essentially same as: -

1 / 19integer division,结果为0。所以表达式本质上是一样的: -

( 20 + ( 0 / 19 ) ) ) / 0

Now you see where the error comes from.

现在您看到错误的来源。



You can add following import in you pythoncode, to enforce floating-point division: -

您可以在python代码中添加以下导入,以强制执行浮点除法:-

from __future__ import division

Or you could cast one of the integers to a float, using either float()or just by adding .0to the initial value.

或者您可以将其中一个整数转换为浮点数,使用float()或仅通过添加.0到初始值。

回答by YardenST

from __future__ import division

and than do your calculation

而不是你的计算

it will cause the division to return floats

它会导致除法返回浮点数

回答by user11156442

This should work. Here's my code:

这应该有效。这是我的代码:

a = 0
b = 17
c = 152
d = 1
e = 133
f = 19
g = 20
h = 0

answer = ( ( ( a / f ) + b + c ) - ( g + ( h / f ) ) ) / ( d / f )

print(answer)

Nearly exactly same.

几乎完全一样。