Tutte le sfide
Facile 0 risolte 0% di accettazione

Array Average

Compute the average of a list of numbers.

Cosa imparerai

  • Sum values and divide by the count
  • Return a decimal result
  • Avoid integer division mistakes

Problema

Mostra traduzione

Return the arithmetic mean of the list: its sum divided by its length, as a decimal number.

Implement array_average(numbers).

Input

numbers: A non-empty list of integers.

Output

Return the average.

Vincoli

1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹

Esempi

Esempio 1
Input:
numbers = [2, 4, 6]

Output atteso:
expected = 4.0
Input:
std::vector<long long> numbers = {2, 4, 6};

Output atteso:
double expected = 4.0;
Input:
long[] numbers = new long[] {2, 4, 6};

Output atteso:
double expected = 4.0;

Spiegazione

(2 + 4 + 6) / 3 = 4.

Esempio 2
Input:
numbers = [1, 2]

Output atteso:
expected = 1.5
Input:
std::vector<long long> numbers = {1, 2};

Output atteso:
double expected = 1.5;
Input:
long[] numbers = new long[] {1, 2};

Output atteso:
double expected = 1.5;

Spiegazione

(1 + 2) / 2 = 1.5; divide as decimals.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

The average comes from combining the whole list into one total and then using its length.

Suggerimento 2

A single pass can collect the sum, then divide by how many values there are.

Suggerimento 3

Be careful to preserve decimal precision instead of using integer division.

Complessità attesa

O(n) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.