除以零误差

发布于 2024-09-24 14:05:29 字数 494 浏览 3 评论 0原文

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

编写一个接收两个参数的函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

所谓喜欢 2024-10-01 14:05:29

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

factor = 60.0 / time_interval

另一种方式将被 60 除以 float(time_interval)

请注意此示例交互:

In [7]: x = 31

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

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

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 saying 60.0 (the float version of 60):

factor = 60.0 / time_interval

Another way would be divide 60 by 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
撞了怀 2024-10-01 14:05:29

Sharth 的意思是:from __future__ import python

示例:

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

Sharth meant to say: from __future__ import python

Example:

>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文