本文將展示如何使用Python編寫程序,輸入圓柱體的半徑和高,計算出它的表面積。
一、輸入圓柱體的半徑和高
首先,我們需要讓用戶輸入圓柱體的半徑和高。可以使用Python內置的input函數來獲取用戶輸入:
radius = float(input("請輸入圓柱體的半徑:"))
height = float(input("請輸入圓柱體的高:"))
這段代碼可以讓用戶輸入圓柱體的半徑和高,並將其保存在變數radius和height中,這裡用float將輸入值轉換為浮點數。
二、計算表面積
圓柱體的表面積由底面積、側面積和頂面積組成。我們可以使用下面的公式計算:
bottom_area = 3.14 * radius * radius
lateral_area = 2 * 3.14 * radius * height
top_area = bottom_area
surface_area = bottom_area + lateral_area + top_area
上面的代碼中,我們首先計算了底面積,然後計算了側面積,最後計算了頂面積。由於圓柱體有兩個底面,所以頂面積與底面積相等。最終,將所有面積相加得到圓柱體的表面積。
三、輸出表面積
最後,我們可以使用print函數將計算結果輸出。
print("圓柱體的表面積為:", surface_area)
這裡使用了逗號分隔符,將輸出的字元串和變數值一起輸出。
完整代碼示例
radius = float(input("請輸入圓柱體的半徑:"))
height = float(input("請輸入圓柱體的高:"))
bottom_area = 3.14 * radius * radius
lateral_area = 2 * 3.14 * radius * height
top_area = bottom_area
surface_area = bottom_area + lateral_area + top_area
print("圓柱體的表面積為:", surface_area)
上面的代碼就是輸入圓柱體的半徑和高,並計算表面積的完整示例。使用Python編寫程序可以使計算更加方便、快捷,同時也是一項很好的編程學習實踐。
原創文章,作者:GESGP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/375179.html