C++程式:計算圓柱體的體積和表面積
圓柱體是一種管狀的3D物體,其底面為圓形,並具有一定的高度。圓柱體的體積實際上是它在空間中佔據的空間大小。在本文中,我們將介紹幾種用C++計算圓柱體體積和表面積的方法。
圓柱體有兩個基本引數:高度h和底面半徑r。圓柱體的表面積可以有兩種變化:只有外曲面(對於空心且兩端開口的圓柱體)和包含曲面以及兩個平面(圓形)面的面積。
圓柱體的體積
要計算圓柱體的體積,我們需要兩個輸入:高度h和半徑r。體積公式如下所示:
$$體積\:=\:\pi\:r^2*h$$
這裡$\pi\:r^2$是底面積,用它乘以h將返回整個體積。現在讓我們看看相應的演算法和實現。
演算法
- 讀取輸入的高度h和半徑r
- 底面積 := $\pi\:r^2$
- 體積 := 底面積 * h
- 返回體積
示例
#include <iostream> using namespace std; float solve( float h, float r ) { float volume; float sa = 3.14159 * r * r; volume = sa * h; return volume; } int main() { cout << "Volume of a cylinder with height h = 5 cm, radius r = 2.5 cm, is " << solve( 5, 2.5 ) << " cm^3" << endl; cout << "Volume of a cylinder with height h = 25 in, radius r = 15 in, is " << solve( 25, 15 ) << " in^3" << endl; }
輸出
Volume of a cylinder with height h = 5 cm, radius r = 2.5 cm, is 98.1747 cm^3 Volume of a cylinder with height h = 25 in, radius r = 15 in, is 17671.4 in^3
圓柱體的側面積
如果我們將圓柱體展開成一個矩形薄片,其中寬度與h相同,長度與2𝜋𝑟(圓周長)相同,則可以計算出只有曲面的面積。在下圖中,我們展示瞭如何將曲面展開成矩形。
$$側面積\:=\:2\pi\:r*h$$
以下演算法用於計算給定圓柱體的側面積:
演算法
- 讀取輸入的高度h和半徑r
- 周長 := $2\pi\:r$
- 面積 := 周長 * h
- 返回面積
示例
#include <iostream> using namespace std; float solve( float h, float r ) { float area; float perimeter = 2 * 3.14159 * r; area = perimeter * h; return area; } int main() { cout << "Curved Surface Area of a cylinder with height h = 5 cm, radius r = 2.5 cm, is " << solve( 5, 2.5 ) << " cm^3" << endl; cout << "Curved Surface Area of a cylinder with height h = 25 in, radius r = 15 in, is " << solve( 25, 15 ) << " in^3" << endl; }
輸出
Curved Surface Area of a cylinder with height h = 5 cm, radius r = 2.5 cm, is 78.5397 cm^3 Curved Surface Area of a cylinder with height h = 25 in, radius r = 15 in, is 2356.19 in^3
圓柱體的全面積
全面積由側面積和圓柱體的兩個圓形底面組成。因此,我們需要將它們與側面積相加才能得到最終的面積。
$$側面積\:=\:2\pi\:r*h$$
$$圓面積\:=\:\pi\:r\:^\:2$$
$$全面積\:=\:(側面積)\:+\:2(圓面積)$$
由於有兩個圓形平面,所以在相加之前我們將圓面積乘以2。這個想法在下圖中進行了描述。與上圖一樣,矩形薄片也在那裡,並且添加了兩個圓形面。在下面的演算法中,我們計算的是相同的。
演算法如下所示:
演算法
- 讀取輸入的高度h和半徑r
- 周長 := $2\pi\:r$
- 圓面積 :=$\pi\:r^2$
- 面積 := (周長 * h) + 2 * 圓面積
- 返回面積
示例
#include <iostream> using namespace std; float solve( float h, float r ) { float area; float perimeter = 2 * 3.14159 * r; float circle_area = 3.14159 * r * r; area = (perimeter * h) + (2 * circle_area); return area; } int main() { cout << "Complete Area of a cylinder with height h = 5 cm, radius r = 2.5 cm, is " << solve( 5, 2.5 ) << " cm^3" << endl; cout << "Complete Area of a cylinder with height h = 25 in, radius r = 15 in, is " << solve( 25, 15 ) << " in^3" << endl; }
輸出
Complete Area of a cylinder with height h = 5 cm, radius r = 2.5 cm, is 117.81 cm^3 Complete Area of a cylinder with height h = 25 in, radius r = 15 in, is 3769.91 in^3
結論
要計算圓柱體的體積和麵積,我們需要兩個引數:圓柱體的底半徑和高度。為了獲得總的體積,首先需要計算底面積,然後將其乘以高度以獲得實際體積。圓柱體的面積有兩種形式:一種是側面積,另一種是全面積,其中我們也考慮了底面的圓形平面。為了計算這一點,我們可以將圓柱體展開成一個高度為h,長度與圓周長相同的矩形薄片,那麼這個矩形的面積就是側面積。要獲得全面積,我們需要將兩個平面面積與側面積相加。在上文的實現中,我們展示了使用一些示例輸入來計算相同值的C++程式。對於每種情況,只需要兩個輸入h和r。