除以零误差
我对教授提出的这个问题有疑问。问题是:
编写一个接收两个参数的函数 Typing_speed 的定义。第一个是一个人在特定时间间隔内键入的单词数(大于或等于零的整数)。第二个是以秒为单位的时间间隔长度(大于零的整数)。该函数返回该人的打字速度,以每分钟字数为单位(float)。
这是我的代码:
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))
我知道“因子”被分配为 0,因为它没有被正确舍入或其他什么。我不知道如何正确处理这些小数。 Float 显然没有做任何事情。
如有任何帮助,我们将不胜感激,谢谢。
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 ).
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.
Any help is appreciated, thankyou.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您对除法结果调用
float
时,事后除法被视为整数除法(注意:我假设这是 Python 2)。这没有帮助,有帮助的是最初将除法指定为浮点除法,例如通过说60.0
(60
的浮点版本):另一种方式将被 60 除以
float(time_interval)
请注意此示例交互:
When you call
float
on the division result, it's after the fact the 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 saying60.0
(the float version of60
):Another way would be divide 60 by
float(time_interval)
Note this sample interaction:
Sharth 的意思是:
from __future__ import python
示例:
Sharth meant to say:
from __future__ import python
Example: