你能在这个 for 循环中使用浮点数吗?

新手上路,请多包涵

我需要一些帮助。我试图让我的 for 循环使用小数,但我的代码不接受浮点数,我不确定下一步该做什么。谁能指出我哪里出错了?

它是用于将用户定义的步骤 (Delta) 中的摄氏温度转换为华氏温度的代码。这里是:

 def main():

    # Handshake
    print("This program will convert a range of Celsius degrees to")
    print("Fahrenheit degrees based on your input.")

    # Ask and read low end of range
    Rangelow = eval(input("Enter the low end of your range: "))

    # Ask and read top end of range
    Rangehigh = 1 + eval(input("Enter the high end of your range: "))

    # Ask and read Delta
    Delta = eval(input("Enter the Delta for your range: "))

    #Display output
    print("Celsius to Fahrenheit by", Delta)
    for i in range(Rangelow, Rangehigh, Delta):
        print(i, "               ", 9/5 * i + 32)

main()

这是我的意思的一个例子:

该程序将根据您的输入将一系列摄氏度转换为华氏度。输入范围的低端:3.8 输入范围的高端:14.7 输入范围的 Delta:1.1 摄氏度到华氏度 1.1 回溯(最近调用最后一次):文件“C:\Users\jarre\Desktop\ Python Programs\Conversion.py”,第 27 行,在 main() 文件“C:\Users\jarre\Desktop\Python Programs\Conversion.py”中,第 22 行,在 main for i in range(Rangelow, Rangehigh + 1, Delta): TypeError: ‘float’ 对象不能解释为整数

我应该注意到问题似乎出在输入上,输出在输入转换后抛出小数点没有问题。

原文由 Jarbcd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 937
2 个回答

您不能使用内置函数来进行浮点数/小数增量,但构建自己的生成器相当容易:

 def decimal_range(start, stop, increment):
    while start < stop: # and not math.isclose(start, stop): Py>3.5
        yield start
        start += increment

for i in decimal_range(Rangelow, Rangehigh, Delta):
    ...

或者您可以使用 numpy 但这感觉就像是用大锤敲打螺母:

 import numpy as np
for i in np.arange(Rangelow, Rangehigh, Delta):
    ...

原文由 AChampion 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是 decimal_range 想法的实现,它涵盖递增和递减,无需转换为 decimal 类,也无需为 none 类型等进行大量验证和处理。

它还将返回停止值本身

def decimal_range(start, stop, increment):
    """
    Like built-in range, but works for floating point numbers
    """
    current = start

    while (start < stop and current < stop) \
          or (start > stop and current > stop) \
          or decimal_is_close(current, stop, increment / 4.0):

        # optional, but useful if you really need to guarantee the stop value itself
        # is returned and not something that is just really really close
        if decimal_is_close(current, stop, increment / 4.0):
            current = stop

        yield current
        current += increment

def decimal_is_close(value, target, what_is_close):
    return abs(value - target) < what_is_close

原文由 ashbygeek 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进