Swift 程序求数的几何平均值
swiftserver side programmingprogramming更新于 2025/9/21 14:22:17
本教程将讨论如何编写 Swift 程序求数的几何平均值。
几何平均值也称为 GM。几何平均值定义为 x 个数乘积的 x 次方根。假设给定数组中有 x 个元素(分别为 a1、a2、a3、....ax),则几何平均值为 −
GM = (a1 * a2 * a3 * a4 * ....*ax)1/x
以下是相同的演示 −
输入
假设给定的输入为 −
MyVal = [34, 67, 2, 45, 8, 12]
输出
期望输出为 −
几何平均值 = 16.413138687438
解释
(34 * 67 * 2 * 45 * 8 * 12)1/6 = (19681920)1/6 = 16.413138687438
公式
以下是几何平均数的公式 -
GM = (a1 * a2 * a3 * a4 * ....*ax)1/x
算法
以下是算法 -
步骤 1 - 创建一个数组。
步骤 2 - 声明一个变量来存储元素的乘积。
步骤 3 - 运行 for从 0 循环到小于数组大小。或者,我们可以迭代每个元素并求它们的乘积。
for x in 0..<arrNums.count{
sum += arrNums[x]
}
步骤 4- 通过计算 x 个数乘积的 x 次方根来求几何平均值。
var GeometricMean = pow(arrProduct, 1/size)
步骤 5- 打印输出
示例 1
以下程序演示如何求这些数的几何平均值。
import Foundation import Glibc // Creating array var MyNumber = [3.4, 5.6, 1.2, 4.0] // To store the product var arrProduct = 1.0 // Finding the product of all the numbers for y in 0..<MyNumber.count{ arrProduct = arrProduct * MyNumber[y] } var size = Double(MyNumber.count) // Finding the geometric mean var GeometricMean = pow(arrProduct, 1/size) print("Array:", MyNumber) print("Geometric Mean:", GeometricMean)
输出
Array: [3.4, 5.6, 1.2, 4.0] Geometric Mean: 3.091911434311368
示例 2
以下程序显示如何找到数字的几何平均值。
import Foundation import Glibc // Function to find the geometric mean func geoMean(arr: [Double])->Double{ let MyNumber = arr // To store the product var arrProduct = 1.0 // Finding the product of all the numbers for y in 0..<MyNumber.count{ arrProduct = arrProduct * MyNumber[y] } let size = Double(MyNumber.count) // Finding the geometric mean let GeometricMean = pow(arrProduct, 1/size) return GeometricMean } // Creating an array var Myval = [5.6, 8.9, 12.3, 5.6, 34.5] print("Array:", Myval) print("Geometric Mean:", geoMean(arr: Myval))
输出
数组:[5.6, 8.9, 12.3, 5.6, 34.5] 几何平均值:10.344227262841542
在上面的代码中,我们有一个名为 Myval 的双精度型数组。现在为了求 Myval 的几何平均值,我们创建了一个名为 geoMean() 的函数。该函数将返回几何平均值。因此,最终的几何平均值为 10.344227262841542。