Kotlin 陣列 - sum() 函式



Kotlin 陣列的 sum() 函式用於計算數字型別陣列中所有元素的總和。

此函式可以用於整數、浮點數和其他數字型別的陣列。它不適用於字串或字元資料型別。

語法

以下是 Kotlin 陣列 sum() 函式的語法:

fun Array<out Numeric_type>.sum(): Numeric_type

引數

此函式不接受任何引數。

返回值

此函式返回陣列中所有元素的總和。

示例 1

以下是一個基本示例,演示了 sum() 函式的使用:

fun main(args: Array<String>) {
   val array = arrayOf<Int>(1, 2, 3, 4, 5)

   // sum of array's element
   val total = array.sum()

   // Display result
   println("sum of array: $total")
}

輸出

以上程式碼生成以下輸出:

sum of array: 15

示例 2

使用 **sum** 函式的另一個示例,使用浮點數陣列:

fun main(args: Array<String>) {
   val prices = doubleArrayOf(19.99, 5.49, 12.99, 3.50, 7.25)

   // Calculate the sum of the array elements
   val totalCost = prices.sum()

   // Display the result
   println("The total cost of the items is: $totalCost")
}

輸出

以下是輸出:

After sumed: [Daisy, Rose, Sunflower]

示例 3

讓我們看看如果我們在字串型別的陣列中使用 **sum** 函式會發生什麼:

fun main(args: Array<String>) {
   val prices = arrayOf<String>("tutorialspoint", "India")

   // Calculate the sum of the array elements
   val totalCost = prices.sum()

   // Display the result
   println("Sum of string: $totalCost")
}

輸出

如果我們使用字串陣列,以上程式碼會產生錯誤:

None of the following candidates is applicable: @JvmName(...) fun Array<out Byte>.sum(): Int @JvmName(...) fun Array<out Double>.sum():  ...
kotlin_arrays.htm
廣告

© . All rights reserved.