Python 除以零误差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3784467/
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 12:44:22  来源:igfitidea点击:

Division by Zero Errors

pythonfloating-pointdecimaldivision

提问by 1337holiday

I have a problem with this question from my professor. Here is the question:

我对教授的这个问题有疑问。这是问题:

Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ).

编写一个函数typing_speed 的定义,它接收两个参数。第一个是一个人在特定时间间隔内输入的字数(整数大于或等于零)。第二个是以秒为单位的时间间隔的长度(一个大于零的整数)。该函数以每分钟字数(浮点数)为单位返回该人的打字速度。

Here is my code:

这是我的代码:

def typing_speed(num_words,time_interval):
    if(num_words >= 0 and time_interval > 0):
        factor = float(60 / time_interval)
        print factor
        return float(num_words/(factor))

I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently.

我知道“因子”被分配为 0,因为它没有被正确四舍五入之类的。我不知道如何正确处理这些小数。Float 显然没有做任何事情。

Any help is appreciated, thankyou.

任何帮助表示赞赏,谢谢。

采纳答案by Eli Bendersky

When you call floaton the division result, it's after the factthe division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0(the float version of 60):

当您调用float除法结果时,这是除法被视为整数除法之后(注意:这是 Python 2,我假设)。它没有帮助,有什么帮助是最初将除法指定为浮点除法,例如说60.0( 的浮点版本60):

factor = 60.0 / time_interval

Another way would be divide 60 by float(time_interval)

另一种方法是将 60 除以 float(time_interval)

Note this sample interaction:

请注意此示例交互:

In [7]: x = 31

In [8]: 60 / x
Out[8]: 1

In [9]: 60.0 / x
Out[9]: 1.935483870967742

回答by gsbabil

Sharth meant to say: from __future__ import python

沙斯想说: from __future__ import python

Example:

例子:

>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>>