我正在尝试制作一个计算气缸体积和表面积的程序; 我目前正在编写它的音量部分.但是,在输出屏幕中,有两位小数.表明:
气缸容积为193019.2896193019.2896cm³
为什么有两个?
之后,我试图让程序询问用户用户想要多少小数位(dp).我怎样才能做到这一点?
这是当前的代码:
print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol" or response =="SA":
pass
else:
print("Please enter a correct statement.")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol":
#Below splits
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.14159 #Making the constant PI
volume = PI*radius*radius*height
print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))
Run Code Online (Sandbox Code Playgroud)
您正在两次插值:
print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))
Run Code Online (Sandbox Code Playgroud)
只需一次就可以:
print("The volume of the cylinder is {}cm\u00b3".format(volume))
Run Code Online (Sandbox Code Playgroud)
关于该.format()函数的好处是你可以告诉它将你的数字格式化为一定数量的小数:
print("The volume of the cylinder is {:.5f}cm\u00b3".format(volume))
Run Code Online (Sandbox Code Playgroud)
它将使用5位小数.该数字也可以参数化:
decimals = 5
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> volume = 193019.2896
>>> decimals = 2
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.29cm³
>>> decimals = 3
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.290cm³
Run Code Online (Sandbox Code Playgroud)
我将离开使用input()并向int()用户询问整数个小数.
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |