Swift 语言程序:查找数字的几何平均数
本教程将讨论如何编写 Swift 程序来查找数字的几何平均数。
几何平均数也称为 GM。几何平均数定义为 x 个数字乘积的 x 次方根。假设我们在给定数组中具有 x 个元素(即,a1、a2、a3、…ax),则几何平均数为 -
GM = (a1 * a2 * a3 * a4 * ....*ax)1/x
以下是相同内容的演示 -
输入
假设我们给定的输入为 -
MyVal = [34, 67, 2, 45, 8, 12]
输出
所需的输出将为 -
Geometric Mean = 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 - 运行一个从 0 到小于数组大小的 for 循环。或者我们可以说迭代每个元素并找到它们的乘积。
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))
输出
Array: [5.6, 8.9, 12.3, 5.6, 34.5] Geometric Mean: 10.344227262841542
在这里,在上面的代码中,我们有一个名为 Myval 的双精度类型数组。现在要找到 Myval 的几何平均数,因此我们创建一个名为 geoMean() 的函数。此函数将返回几何平均数。因此,得到的几何平均数为 10.344227262841542。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP