C++程式計算立方體的體積
立方體是基本的3D物體,具有8個頂點、12條邊和6個面。3D物體的體積是指它在空間中佔據的空間大小。在本文中,我們將瞭解如何透過編寫C++程式來計算立方體的體積。
立方體的所有邊長都相等。每個面的面積為𝑘2,其中𝑘是每條邊的長度。由於3D物體具有長、寬、高,因此其體積將為𝑘3。讓我們看看計算立方體體積的演算法和相應的C++實現。
演算法
- 獲取立方體邊長,記為k。
- 體積 := k^3.
- 返回體積。
示例
#include <iostream> using namespace std; int solve( int k ) { int volume; volume = k * k * k; return volume; } int main() { cout << "Volume of a cube with side length k = 5 cm, is " << solve( 5 ) << " cm^3" << endl; cout << "Volume of a cube with side length k = 2 m, is " << solve( 2 ) << " m^3" << endl; cout << "Volume of a cube with side length k = 25 in, is " << solve( 25 ) << " in^3" << endl; }
輸出
Volume of a cube with side length k = 5 cm, is 125 cm^3 Volume of a cube with side length k = 2 m, is 8 m^3 Volume of a cube with side length k = 25 in, is 15625 in^3
立方體的體積也可以使用其對角線來計算。對角線與面的對角線不同。立方體對角線是指相對兩個遠角之間的直線,並穿過立方體的中心。請參閱下圖以更好地理解。
這裡每條邊長為“a”,對角線長度為“d”。根據邊長,我們可以計算對角線的長度,即−
$$d\:=\:\sqrt{3}\:*\:a$$
當已知𝑑的值時,我們可以使用一個簡單的公式計算體積,如下所示−
$$Volume\:=\:\sqrt{3}\:*\frac{d^3}{9}$$
這個公式非常簡單。如果我們在此處替換$d\:=\:\sqrt{3}\:*\:a$,則公式變為。
$$Volume\:=\:\sqrt3*\frac{(\sqrt3*\:a)^3}{9}$$
$$Volume\:=\:\sqrt3*\frac{3\sqrt3*\:a^3}{9}$$
$$Volume\:=\:\frac{9a^3}{9}$$
$$Volume\:=\:a^3$$
這與我們之前看到的公式相同。
現在讓我們看看這個公式的C++實現,其中我們將立方體的對角線作為輸入,並使用上述公式計算體積。
演算法
- 獲取立方體的對角線d。
$Volume\:=\:\sqrt{3}\:*\frac{d^3}{9}$.
- 返回體積。
示例
#include <iostream> #include <cmath> using namespace std; float solve( float d ) { float volume; volume = sqrt(3) * (d * d * d) / 9; return volume; } int main(){ cout << "Volume of a cube with diagonal length d = 1.732 cm, is " << solve( 1.732 ) << " cm^3" << endl; cout << "Volume of a cube with diagonal length d = 5 cm, is " << solve( 5 ) << " cm^3" << endl; cout << "Volume of a cube with diagonal length d = 2.51 cm, is " << solve( 2.51 ) << " cm^3" << endl; }
輸出
Volume of a cube with diagonal length d = 1.732 cm, is 0.999912 cm^3 Volume of a cube with diagonal length d = 5 cm, is 24.0563 cm^3 Volume of a cube with diagonal length d = 2.51 cm, is 3.04326 cm^3
結論
計算立方體的體積是一個非常簡單的過程,我們只需要對立方體邊長進行三次方運算(求三次冪)。有時我們可能不知道立方體的邊長,但如果我們知道對角線長度,也可以計算立方體的體積。我們已經討論了這兩種計算立方體體積的方法。要使用對角線,在C++中我們需要使用平方根運算,這可以透過呼叫cmath庫中提供的sqrt()方法來完成。我們還可以使用pow()函式進行三次方運算。但是在這裡,我們透過將值乘以三次來計算三次方。