C++程式:計算球體的體積和表面積


球體是一種球狀的3D物體,其所有側面都是曲面。球體上不存在任何平面。球體的體積實際上是它在空間中佔據的空間大小。在本文中,我們將介紹使用C++計算球體體積和表面積的技術。

球體有一個基本引數:半徑r。我們將分別介紹計算體積和表面積的技術。

球體的體積

要計算球體的體積,我們需要一個輸入:半徑r。體積公式如下:

$$體積\:=\:\frac{4}{3}\pi\:r^3$$


現在讓我們看看相應的演算法和實現。

演算法

  • 讀取半徑r作為輸入。
  • 體積 := $\frac{4}{3}\pi\:r^3$。
  • 返回體積。

示例

#include <iostream> using namespace std; float solve( float r ) { float volume; volume = ( 4 / 3 ) * 3.14159 * ( r * r * r); return volume; } int main() { cout << "Volume of a sphere with radius r = 2.5 cm, is " << solve( 2.5 ) << " cm^3" << endl; cout << "Volume of a sphere with radius r = 5in, is " << solve( 5 ) << " in^3" << endl; }

輸出

Volume of a sphere with radius r = 2.5 cm, is 49.0873 cm^3
Volume of a sphere with radius r = 5in, is 392.699 in^3

球體的表面積

球體只有一個曲面,沒有其他平面。根據半徑,我們可以透過以下簡單公式計算表面積:

$$表面積\:=\:4\pi\:r^2$$

以下是計算給定球體表面積的演算法:

演算法

  • 讀取半徑r作為輸入。
  • 面積 := $4\pi\:r^2$。
  • 返回面積。

示例

#include <iostream> using namespace std; float solve( float r ) { float volume; volume = 4 * 3.14159 * ( r * r ); return volume; } int main() { cout << "Surface Area of a sphere with radius r = 2.5 cm, is " << solve( 2.5 ) << " cm^3" << endl; cout << "Surface Area of a sphere with radius r = 5in, is " << solve( 5 ) << " in^3" << endl; }

輸出

Surface Area of a sphere with radius r = 2.5 cm, is 78.5397 cm^3
Surface Area of a sphere with radius r = 5in, is 314.159 in^3

結論

球體是3D世界中的球狀結構。與其他3D物體一樣,我們可以計算球體的體積和表面積。對於球體,直徑或半徑足以表達球體。根據直徑或半徑,我們可以計算曲面的面積和球體的體積。這兩個公式都非常簡單。在給定的實現中,直接使用了相同的公式。

更新於:2022年10月17日

7000+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.