如何舍入函数输出的值?

2024-10-06 09:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个代码,将节数转换为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)


Tags: thetoingoreturnifdefspeed
3条回答

您应该只在显示时进行取整,并且可以通过对f字符串变量使用:.1f来实现这一点:

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):.1f} - Go faster!')
elif to_kmh(knots) <100:
    print(f'{to_kmh(knots):.1f} - Nice one.')
elif to_kmh(knots) >=100:
    if to_kmh(knots) <120:
    print(f'{to_kmh(knots):.1f} - Radical!')
if to_kmh(knots) >120: 
    print(f'{to_kmh(knots):.1f} - Whoa! Slow down!')

另一个避免重复的选项是让to_kmh返回格式化字符串而不是数字

或者,如果您真的想从函数中取整数字(不能保证结果是您想要的):

def to_kmh(knots):
  return round(1.852 * knots, 1)

你的错误是你试图在return之后round

必须在return语句之前使用round()。在函数中,执行return语句之后的任何内容都不会执行

所以把你的代码改成

return round(1.852 * knots, 1)

它应该很好用

返回值时不要舍入,格式化输出时要舍入

kmh = to_kmh(knots)
if kmh <60:
    print(f'{kmh:.1f} - Go faster!')
elif kmh <100:
    print(f'{kmh:.1f} - Nice one.')
elif kmh <120:
      print(f'{kmh:.1f} - Radical!')
else:
    print(f'{kmh:.1f} - Whoa! Slow down!')

也不需要测试>= 100,因为前面的elif保证了这一点。最后的测试应该是else:,以获得所有更高的值

相关问题 更多 >