kotlin 数组加元素_Kotlin程序查找数组元素的和和平均值

kotlin 数组加元素

Given a double type array, we have to find sum and average of its all elements.

给定一个双精度型数组,我们必须找到其所有元素的总和和平均值。

Example:

例:

    Input:
    arr = [4.0, 56.0, 7.0, 8.0, 43.0, 2.0, 3.0]

    Output:
    sum = 123.0
    average = 17.571428571428573

程序在Kotlin中查找数组元素的和和平均值 (Program to find sum and average of array elements in Kotlin)

package com.includehelp

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val s = Scanner(System.`in`)

    //Input Array Size
    print("Enter number of elements in the array: ")
    val size = s.nextInt()

    //Create Double array of Given size
    val doubleArray = DoubleArray(size)

    //Input array elements
    println("Enter Arrays Elements:")
    for (i in doubleArray.indices) {
        print("doubleArray[$i] : ")
        doubleArray[i] = s.nextDouble()
    }

    //declare variable for sum of elements
    var sum: Double=0.toDouble()

    for (i in doubleArray.indices) {
        //add array element in sum
        sum+=doubleArray[i]
    }

    //Avg of elements
    var avg=sum/doubleArray.size

    //Alternatively we can also use sum() and average() method of Arrays Class in
    //var sum = doubleArray.sum()
    //var avg = doubleArray.average()

    println("Array : ${doubleArray.contentToString()} ")
    println("Sum of Elements : $sum")
    println("Average of Elements : $avg")
}

Output

输出量

Run 1:
-----
Enter number of elements in the array: 7
Enter Arrays Elements:
doubleArray[0] : 4
doubleArray[1] : 56
doubleArray[2] : 7
doubleArray[3] : 8
doubleArray[4] : 43
doubleArray[5] : 2
doubleArray[6] : 3
Array : [4.0, 56.0, 7.0, 8.0, 43.0, 2.0, 3.0]
Sum of Elements : 123.0
Average of Elements : 17.571428571428573
--------
Run 2:
----
Enter number of elements in the array: 6
Enter Arrays Elements:
doubleArray[0] : 45.32
doubleArray[1] : 5.7
doubleArray[2] : 9.21
doubleArray[3] : 9.6
doubleArray[4] : 34.98
doubleArray[5] : 6.54
Array : [45.32, 5.7, 9.21, 9.6, 34.98, 6.54]
Sum of Elements : 111.35000000000001
Average of Elements : 18.558333333333334


翻译自: https://www.includehelp.com/kotlin/find-sum-and-average-of-array-elements.aspx

kotlin 数组加元素

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值