2013-10-03 55 views
0

我試圖使這個程序,其計算的氣缸的體積和表面積;我目前正在編寫卷的一部分。但是,在輸出屏幕中,有兩位小數。它顯示:Python中的兩個小數?

氣缸的容積is193019.2896193019.2896cm³

爲什麼有兩個?

在那之後,我試圖讓程序問多少個小數位(露點)用戶想要的用戶。我怎樣才能做到這一點?

下面是當前的代碼:

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

回答

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

有關的好處功能是你可以告訴它將您的號碼格式化爲一定的小數位數:

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()索要小數從用戶給你一個整數。

+0

一點題外話,把一個值時,'打印內部()'函數,你並不需要顯式調用' str()','print()'函數會自動執行此操作。 (好吧,它得到了對象的'__str__'屬性,這是'str()'調用的)。編輯:只有當不使用fn內的字符串concat。 – gos1

+1

@ gos1:不是在使用'+'先連接值時。 –

+0

這是當我做太多的Java和沒有足夠的Python時所得到的,謝謝! – gos1

0

回答有關詢問用戶的問題多少個小他想:

#! /usr/bin/python3 

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

沒有必要去那個長度;你可以直接使用* one *'.format()'調用。看到我的答案。 –

+0

Neat ............ – Hyperboreus