简体   繁体   中英

Finding a Average of an Array of Integer

I have this code

    Dim intPerson As Integer

    For Each intPerson In intAge

    Next

intPerson holds a different number every time the loop is executed because intAge is an array. Is there a way I can find the average of intPerson by adding each number each time and then dividing it by the amount of numbers there are in the array?

The easiest way is to use Linq:

    'create an array with some sample ages
    Dim intAge As Integer() = {22, 34, 56, 87, 19}
    'find the average
    Dim averageAge = intAge.Average 'averageAge = 43.6

If you wanto do this longhand you can sum up the values and divide by the number:

    Dim totalAges As Integer = 0
    For i As Integer = 0 To intAge.Count - 1
        totalAges += intAge(i)
    Next
    averageAge = totalAges / intAge.Count 'averageAge = 43.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM