如何舍入函数输出的值?

How do I round the value my function outputs?

我正在编写将结转换为 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) 四舍五入到小数点后一位。示例:当我在程序中输入“3 knots”时,我得到:

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)。

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

所以将您的代码更改为

return round(1.852 * knots, 1)

它应该可以正常工作!!

你应该只在显示时四舍五入,你可以在你的 f-string 变量上使用 :.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 return 格式化为字符串而不是数字。

或者,如果你真的想对函数中的数字进行四舍五入(不保证结果就是你想要的):

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

您的错误是您在 return 之后尝试 round

返回值时不进行舍入,在格式化输出时进行。

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: 以获得所有更高的值。