【问题标题】:How do change my program so that it always rounds to the nearest 2 decimal places)如何更改我的程序,使其始终四舍五入到最接近的 2 位小数)
【发布时间】:2021-12-05 03:56:16
【问题描述】:

#.这个程序会根据用户给定的半径找到一个圆的面积和周长。

导入数学

radius=int(input('输入半径的数字'))

area=math.pi半径2

print('圆的面积%f'%area)

周长= 2math.pi半径

print('圆的周长 %f'% 周长)

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    打印时使用%.2f,而不是%f,四舍五入到小数点后两位。

    【讨论】:

      【解决方案2】:

      Python 有一个 round 关键字。像这样使用它:

      round(3.14159, 2)
      >>> 3.14
      

      或者,您可以在打印时使用 python f-strings 进行舍入,如下所示:

      num = 3.14159
      print(f'{num:.2f}')
      >>> 3.14
      

      【讨论】:

      • 注意:到目前为止,这个问题被标记为 Python 2.7,Python 2.7 不支持 f-string 系统。如果您使用的是 Python 3,那么 f-strings 绝对是最佳选择。
      猜你喜欢
      • 2014-05-24
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多