0

我正在尝试制作这个计算圆柱体的体积和表面积的程序;我目前正在编码它的音量部分。但是,在输出屏幕中,有两位小数。表明:

圆柱体体积为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))
4

2 回答 2

9

您正在对值进行两次插值:

print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))

只需一次即可:

print("The volume of the cylinder is {}cm\u00b3".format(volume))

这个.format()函数的好处是你可以告诉它把你的数字格式化为一定的小数位数:

print("The volume of the cylinder is {:.5f}cm\u00b3".format(volume))

它将使用 5 位小数。该数字也可以参数化:

decimals = 5
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

演示:

>>> 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³

我将继续使用input()int()要求用户提供整数位数的小数,直到你。

于 2013-10-03T20:56:11.427 回答
0

要回答您关于询问用户他想要多少小数的问题:

#! /usr/bin/python3

decimals = int (input ('How many decimals? ') )
print ('{{:.{}f}}'.format (decimals).format (1 / 7) )
于 2013-10-03T21:01:08.710 回答