Swift程序:计算球体的体积和表面积


本教程将讨论如何编写一个Swift程序来计算球体的体积和表面积。

球体是一种三维的圆形立体形状或物体。或者我们可以说球体是在三个轴上定义的形状:x轴、y轴和z轴。它没有任何顶点或边。

球体的体积

球体在三维平面中占据的空间量称为球体的体积。例如,我们想用液体填充一个球形球,因此可以使用体积来计算所需的液体量。

公式

以下是体积公式:

Volume = 4πr3/3

下面是相同的演示:

输入

假设我们给定的输入是:

Radius = 3

输出

期望的输出将是:

Volume = 50

算法

以下是算法:

  • 步骤1 - 声明一个双精度型变量来存储球体的半径。

var sRadius : Double = 4.0
  • 步骤2 - 使用数学公式声明另一个变量来存储球体的体积:

var sVolume = (4 * Double.pi * sRadius * sRadius * sRadius)/3
  • 步骤3 - 打印输出。

示例

下面的程序演示了如何找到球体的体积。

Open Compiler
import Foundation import Glibc var sRadius : Double = 4.0 // Calculating the volume of the sphere var sVolume = (4 * Double.pi * sRadius * sRadius * sRadius)/3 print("Radius of the sphere is:", sRadius) print("Hence the volume of the sphere is:", sVolume)

输出

Radius of the sphere is: 4.0 
Hence the volume of the sphere is: 268.082573106329

在上面的代码中,我们使用以下代码计算球体的体积:

var sVolume = (4 * Double.pi * sRadius * sRadius * sRadius)/3

显示球体的体积,结果为 268.082573106329 (体积 = (4 * 3.141592653589793 * 4.0 * 4.0 * 4.0)/3 = 268.082573106329)。

球体的表面积

球体在三维平面中覆盖的总空间或区域称为球体的表面积。

公式

以下是球体表面积的公式:

Area = 4πr2

下面是相同的演示:

输入

假设我们给定的输入是:

Radius = 2

输出

期望的输出将是:

Area = 50.26548245743669

算法

以下是算法:

  • 步骤1 - 声明一个双精度型变量来存储球体的半径。

var sRadius : Double = 6.0
  • 步骤2 - 使用数学公式声明另一个变量来存储球体的表面积:

var sArea = 4 * Double.pi * sRadius * sRadius
  • 步骤3 - 打印输出。

示例

下面的程序演示了如何找到球体的表面积。

Open Compiler
import Foundation import Glibc var sRadius : Double = 6.0 // Calculating the area of the sphere var sArea = 4 * Double.pi * sRadius * sRadius print("Radius of the sphere is:", sRadius) print("Hence the area of the sphere is:", sArea)

输出

Radius of the sphere is: 6.0
Hence the area of the sphere is: 452.3893421169302

在上面的代码中,我们使用以下代码计算球体的表面积:

var sArea = 4 * Double.pi * sRadius * sRadius

显示球体的表面积,结果为 452.3893421169302 (表面积 = 4 * 3.141592653589793 * 6.0 * 6.0 = 452.3893421169302)。

更新于:2022年8月25日

浏览量:300

启动你的职业生涯

通过完成课程获得认证

开始学习
广告