函数 Celsius2Fahrenheit 会将摄氏度转换为华氏度以供以后使用,并且范围应该每次上升 .5,并停止在 101,但你不能在范围内使用浮点值,(我是 python 的初学者(,有人可以帮忙吗?
def Celsius2Fahrenheit(c):
""" This will Convert c Celsius to its Fahrenheit equivalent"""
return c * 9 / 5 + 32
for x in range(0,101,.5):
# This will print the values using new style formatting
e = Celsius2Fahrenheit(x)
if (e > 0):
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
else:
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
以下是两种可能性:
1(将您的范围乘以10,以便这些值成为您可以与range()
一起使用的整数。然后,您将索引变量除以 10 以返回您所追求的浮点值,如下所示:
for ix in range(0, 1010, 5):
x = ix / 10
<...rest of your code...>
2(您可以使用numpy
中的arange()
方法:
import numpy
for x in numpy.arange(0, 5.5, 0.5):
e = Celsius2Fahrenheit(x)
<...rest of your code...>
有关arange()
的更多详细信息,请参阅参考资料
因为您可以像这样增加范围。
试试这个,
import numpy as np
def Celsius2Fahrenheit(c):
#This will Convert c Celsius to its Fahrenheit equivalent"""
return c * 9 / 5 + 32
使用麻皮橙,
for x in np.arange(0, 101, 0.5):
# This will print the values using new style formatting
e = Celsius2Fahrenheit(x)
if (e > 0):
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
else:
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
有两种基本方法可以做到这一点,使用 while 循环并自己修改值,或者更改范围函数的边界。
第一种方法可能是首选,因为它会更准确且易于编码。
def Celsius2Fahrenheit(c):
""" This will Convert c Celsius to its Fahrenheit equivalent"""
return c * 9 / 5 + 32
"""While Loop Method"""
x = 0
while x <= 100:
e = Celsius2Fahrenheit(x)
if (e > 0):
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
else:
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
x += 0.5
print()
"""Higher Range"""
import math
step = 0.5
for x in range(0,math.ceil(100.5/step)):
e = Celsius2Fahrenheit(x*step)
if (e > 0):
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
else:
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
请注意,对于第二种方法,最好的方法是将步长值添加到范围的上限。 例如:
for x in range(0,math.ceil((100+step)/step)):
这将上升到非阶跃值(在本例中为 100(。
试试这个
def Celsius2Fahrenheit(c):
return c * 9 / 5 + 32
for x in map(lambda x: x/10.0, range(0, 1005, 5)):
# This will print the values using new style formatting
e = Celsius2Fahrenheit(x)
if (e > 0):
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
else:
print(" {:3.1f} (C) | {:6.2f} (F) ".format(x,e))
这将以 .5 的步长创建从 0 到 100 的值列表