Python中的两个小数?

时间:2013-10-03 20:54:19

标签: python decimal

我正在尝试制作一个计算气缸体积和表面积的程序;我目前正在编写它的音量部分。但是,在输出屏幕中,有两位小数。它显示:

  

气缸容积为193019.2896193019.2896cm³

为什么有两个?

之后,我试图让程序询问用户用户想要多少小数位(d.p.)。我怎么能这样做?

以下是当前代码:

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

2 个答案:

答案 0 :(得分: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()离开,要求用户提供一个整数小数。

答案 1 :(得分:0)

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

#! /usr/bin/python3

decimals = int (input ('How many decimals? ') )
print ('{{:.{}f}}'.format (decimals).format (1 / 7) )