Python程式:計算球體的體積和表面積
球體(實心球)通常被認為是二維圖形,即使該圖形從其中心在三個平面上可見。其主要原因是球體僅使用其半徑進行測量。
然而,空心球被認為是三維圖形,因為它在其球形壁內包含空間,並具有兩個不同的半徑來測量其尺寸。

球形圖形只有總表面積,因為只有一個維度可以測量整個物體。計算球體表面積的公式為:
實心球的表面積 − $\mathrm{{4\pi r^2}}$
球體的體積被認為是物體圓形壁所容納的質量。計算球體體積的公式為:
實心球的體積 − $\mathrm{{\frac{4}{3}\pi r^3}}$
空心球的體積 − $\mathrm{{\frac{4}{3}\pi(R\:-\:r)^3}}$
其中,R是外球的半徑,r是內球的半徑。

輸入輸出場景
讓我們來看一些計算球體面積和體積的輸入輸出場景:
假設要查詢的面積和體積是實心球的:
Input: 7 // 7 is the radius Result: Area - 314.1592653589793 Volume - 359.188760060433
假設要查詢的面積和體積是空心球的:
Input: (7, 5) // 7 is the outer radius, 5 is the inner radius Result: Area - 314.1592653589793 // Area is same Volume - 100.53096491487338
使用數學公式
在Python程式中,我們使用討論過的數學公式來計算球體的面積和體積。我們匯入math庫來使用pi常量。
示例
以下是查詢球形3D圖形的面積和體積的示例:
import math R = 7 #outer radius of sphere r = 5 # inner radius of sphere #calculating area of solid sphere area = 4*(math.pi)*(r)*(r) #calculating volume of hollow sphere volume_hollow = 4*(math.pi)*(R - r)*(R - r)*(R - r) #calculating volume of solid sphere volume_solid = (1/3)*(math.pi)*(R)*(R)*(R) #displaying output print("Area of the sphere: ", str(area)) print("Volume of the hollow sphere: ", str(volume_hollow)) print("Volume of the solid sphere: ", str(volume_solid))
輸出
輸出結果如下所示:
Area of the sphere: 314.1592653589793 Volume of the hollow sphere: 100.53096491487338 Volume of the solid sphere: 359.188760060433
計算面積和體積的函式
Python還使用函式來提高程式的模組化。在這種情況下,我們使用一個計算球體面積和體積的函式。
示例
在下面的Python程式中,我們使用使用者定義的函式計算實心球和空心球的面積和體積:
import math def sphere_area_volume(R, r): #calculating area of solid sphere area = 4*(math.pi)*(r)*(r) #calculating volume of hollow sphere volume_hollow = 4*(math.pi)*(R - r)*(R - r)*(R - r) #calculating volume of solid sphere volume_solid = (1/3)*(math.pi)*(R)*(R)*(R) #displaying output print("Area of the sphere: ", str(area)) print("Volume of the hollow sphere: ", str(volume_hollow)) print("Volume of the solid sphere: ", str(volume_solid)) R = 7 #outer radius of sphere r = 5 # inner radius of sphere sphere_area_volume(R, r)
輸出
執行上述程式碼後,將獲得以下輸出:
Area of the sphere: 314.1592653589793 Volume of the hollow sphere: 100.53096491487338 Volume of the solid sphere: 359.188760060433
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP