函数Celsius2Fahrenheit将Celsius转换为Fahrenheit以便稍后使用,并且该范围应该每次增加.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()
一起使用的整数。然后,将index变量除以10,即可得到您想要的float值,如下所示:
for ix in range(0, 1010, 5):
x = ix / 10
<...rest of your code...>
2)您可以改为使用arange()
中的numpy
方法:
import numpy
for x in numpy.arange(0, 5.5, 0.5):
e = Celsius2Fahrenheit(x)
<...rest of your code...>
有关reference的更多详细信息,请参见arange()
因为您可以像这样增加范围。
尝试一下,
import numpy as np
def Celsius2Fahrenheit(c):
#This will Convert c Celsius to its Fahrenheit equivalent"""
return c * 9 / 5 + 32
使用numpy arange,
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循环并自己修改值,或者更改range函数的界限。
第一种方法可能更可取,因为它将更加准确并且易于编码。
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的值列表