【问题标题】:Issue with a function功能问题
【发布时间】:2020-09-12 06:26:03
【问题描述】:

用户输入KGs(例如1800),应该转换成立方米,函数应该返回结果。

这是我的代码:

def volume_per_container(kg_cargo_per_cubic_metre):
    """Given the kg of cargo per cubic metre, calculate how many cubic metres
    of cargo can be stored in a single container."""
    max_volume_cubic_metres = 65.7
    max_net_load = 26199

    cubic_metre = kg_cargo_per_cubic_metre / max_net_load
    if cubic_metre >= 65.7:
        return volume_per_container (kg_cargo_per_cubic_metre) == max_volume_cubic_metres
    else:
        return volume_per_container (kg_cargo_per_cubic_metre) == cubic_metre

我收到此错误:

RecursionError: 比较中超出了最大递归深度

我该如何解决这个问题?

【问题讨论】:

  • 你调用函数本身,然后调用它本身等等。
  • 你的算法是错误的。您总是在函数的末尾一次又一次地调用该函数,并且当您调用它的次数超过 Python 默认允许的次数时(您可以通过 sys.setrecursionlimit(...) 更改此值,尽管它不会导致您的特定问题) ,你会得到 RecursionError。
  • 您介意将问题的标题更改为更丰富的内容吗? “函数问题”非常模糊。

标签: python recursion


【解决方案1】:

你想这样做吗:

def volume_per_container(kg_cargo_per_cubic_metre):
    """Given the kg of cargo per cubic metre, calculate how many cubic metres
    of cargo can be stored in a single container."""
    max_volume_cubic_metres = 65.7
    max_net_load = 26199

    cubic_metre = kg_cargo_per_cubic_metre / max_net_load
    if cubic_metre >= max_volume_cubic_metres:
     return cubic_metre - max_volume_cubic_metres
    else:
     print("this much left to fill")
     return max_volume_cubic_metres - cubic_metre

【讨论】:

  • 感谢您的帮助我现在已经弄清楚了
猜你喜欢
  • 1970-01-01
  • 2016-03-09
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 2016-09-14
相关资源
最近更新 更多