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。

更新於: 2022 年 10 月 20 日

263 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.