我正在写一个代码,将节数转换为km/h
def to_kmh(knots):
# Calculate the speed in km/h
return 1.852 * knots
# Write the rest of your program here
knots = float(input('Speed (kn): '))
if to_kmh(knots) <60:
print(f'{to_kmh(knots)} - Go faster!')
elif to_kmh(knots) <100:
print(f'{to_kmh(knots)} - Nice one.')
elif to_kmh(knots) >=100:
if to_kmh(knots) <120:
print(f'{to_kmh(knots)} - Radical!')
if to_kmh(knots) >120:
print(f'{to_kmh(knots)} - Whoa! Slow down!')
我试图将输出(km/h)四舍五入到小数点后1位。示例:当我在程序上键入“3节”时,我得到:
5.556 - Go faster!
而我想
5.6 - Go faster!
我试过使用
def to_kmh(knots):
# Calculate the speed in km/h
return 1.852 * knots
round(to_kmh, 1)
在函数中,但输出相同的结果(5.556)
您应该只在显示时进行取整,并且可以通过对f字符串变量使用
:.1f
来实现这一点:另一个避免重复的选项是让
to_kmh
返回格式化字符串而不是数字或者,如果您真的想从函数中取整数字(不能保证结果是您想要的):
你的错误是你试图在
return
之后round
必须在
return
语句之前使用round()
。在函数中,执行return
语句之后的任何内容都不会执行所以把你的代码改成
它应该很好用
返回值时不要舍入,格式化输出时要舍入
也不需要测试
>= 100
,因为前面的elif
保证了这一点。最后的测试应该是else:
,以获得所有更高的值相关问题 更多 >
编程相关推荐