Promedio de una secuencia de números

Nivel de dificultad: Novato

Dada una secuencia de números, imprima el promedio (o la media) de la secuencia en cada punto. Por ejemplo, consideremos la corriente como 10, 20, 30, 40, 50, 60, …

  Average of 1 numbers is 10.00
  Average of 2 numbers is 15.00
  Average of 3 numbers is 20.00
  Average of 4 numbers is 25.00
  Average of 5 numbers is 30.00
  Average of 6 numbers is 35.00
  ..................

Para imprimir la media de un flujo, necesitamos averiguar cómo encontrar el promedio cuando se agrega un nuevo número al flujo. Para hacer esto, todo lo que necesitamos es el conteo de números vistos hasta ahora en la transmisión, el promedio anterior y el nuevo número. Sea n el conteo, prev_avg el promedio anterior yx el nuevo número que se agrega. El promedio después de incluir el número x se puede escribir como (prev_avg*n + x)/(n+1) .

Producción : 

Average of 1 numbers is 10.000000 
Average of 2 numbers is 15.000000 
Average of 3 numbers is 20.000000 
Average of 4 numbers is 25.000000 
Average of 5 numbers is 30.000000 
Average of 6 numbers is 35.000000 

Complejidad de tiempo: O(n)

Espacio Auxiliar: O(1)

La función anterior getAvg() se puede optimizar usando los siguientes cambios. Podemos evitar el uso de prev_avg y el número de elementos mediante el uso de variables estáticas (suponiendo que solo se llame a esta función para un promedio de flujo). La siguiente es la versión optimizada. 

C++

#include <bits/stdc++.h>
using namespace std;
 
// Returns the new average after including x
float getAvg(int x)
{
    static int sum, n;
 
    sum += x;
    return (((float)sum) / ++n);
}
 
// Prints average of a stream of numbers
void streamAvg(float arr[], int n)
{
    float avg = 0;
    for (int i = 0; i < n; i++)
    {
        avg = getAvg(arr[i]);
        cout<<"Average of "<<i+1<<" numbers is "<<fixed<<setprecision(1)<<avg<<endl;
    }
    return;
}
 
// Driver code
int main()
{
    float arr[] = { 10, 20, 30, 40, 50, 60 };
    int n = sizeof(arr) / sizeof(arr[0]);
    streamAvg(arr, n);
 
    return 0;
}
 
// This code is contributed by rathbhupendra

C

#include <stdio.h>
 
// Returns the new average after including x
float getAvg(int x)
{
    static int sum, n;
 
    sum += x;
    return (((float)sum) / ++n);
}
 
// Prints average of a stream of numbers
void streamAvg(float arr[], int n)
{
    float avg = 0;
    for (int i = 0; i < n; i++) {
        avg = getAvg(arr[i]);
        printf("Average of %d numbers is %f \n", i + 1, avg);
    }
    return;
}
 
// Driver program to test above functions
int main()
{
    float arr[] = { 10, 20, 30, 40, 50, 60 };
    int n = sizeof(arr) / sizeof(arr[0]);
    streamAvg(arr, n);
 
    return 0;
}

Java

// Java program to return
// Average of a stream of numbers
class GFG
{
static int sum, n;
     
// Returns the new average
// after including x
static float getAvg(int x)
{
    sum += x;
    return (((float)sum) / ++n);
}
 
// Prints average of a
// stream of numbers
static void streamAvg(float[] arr,
                      int n)
{
    float avg = 0;
    for (int i = 0; i < n; i++)
    {
        avg = getAvg((int)arr[i]);
        System.out.println("Average of "+ (i + 1) +
                           " numbers is " + avg);
    }
    return;
}
 
// Driver Code
public static void main(String[] args)
{
    float[] arr = new float[]{ 10, 20, 30,
                               40, 50, 60 };
    int n = arr.length;
    streamAvg(arr, n);
}
}
 
// This code is contributed by mits

Python3

# Returns the new average
# after including x
def getAvg(x, n, sum):
    sum = sum + x;
    return float(sum) / n;
 
# Prints average of a
# stream of numbers
def streamAvg(arr, n):
    avg = 0;
    sum = 0;
    for i in range(n):
        avg = getAvg(arr[i], i + 1, sum);
        sum = avg * (i + 1);
        print("Average of ", end = "");
        print(i + 1, end = "");
        print(" numbers is ", end = "");
        print(avg);
    return;
 
# Driver Code
arr= [ 10, 20, 30,
       40, 50, 60 ];
n = len(arr);
streamAvg(arr,n);
 
# This code is contributed by mits

C#

using System;
 
class GFG
{
static int sum, n;
     
// Returns the new average
// after including x
static float getAvg(int x)
{
 
    sum += x;
    return (((float)sum) / ++n);
}
 
// Prints average of a
// stream of numbers
static void streamAvg(float[] arr, int n)
{
    float avg = 0;
    for (int i = 0; i < n; i++)
    {
        avg = getAvg((int)arr[i]);
        Console.WriteLine("Average of {0} numbers " +
                             "is {1}", (i + 1), avg);
    }
    return;
}
 
// Driver Code
static int Main()
{
    float[] arr = new float[]{ 10, 20, 30,
                               40, 50, 60 };
    int n = arr.Length;
    streamAvg(arr, n);
 
    return 0;
}
}
 
// This code is contributed by mits

PHP

<?php
// Returns the new average
// after including x
function getAvg($x)
{
    static $sum;
    static $n;
    $sum += $x;
    return (((float)$sum) / ++$n);
}
 
// Prints average of
// a stream of numbers
function streamAvg($arr, $n)
{
    for ($i = 0; $i < $n; $i++)
    {
        $avg = getAvg($arr[$i]);
        echo "Average of " . ($i + 1) .
             " numbers is ".$avg." \n";
    }
    return;
}
 
// Driver Code
$arr = array(10, 20, 30,
             40, 50, 60);
$n = sizeof($arr) / sizeof($arr[0]);
streamAvg($arr, $n);
 
// This code is contributed by mits
?>

Javascript

<script>
// javascript program to return
// Average of a stream of numbers
 
    var sum=0, n=0;
 
    // Returns the new average
    // after including x
    function getAvg(x) {
        sum += x;
        n++;
        return (sum / n);
    }
 
    // Prints average of a
    // stream of numbers
    function streamAvg( arr , m) {
        var avg = 0;
        for (i = 0; i < m; i++) {
            avg = getAvg(parseInt(arr[i]));
            document.write("Average of " + (i + 1) + " numbers is " + avg.toFixed(1)+"<br/>");
        }
        return;
    }
 
    // Driver Code
     
        var arr =  [ 10, 20, 30, 40, 50, 60 ];
        var m = arr.length;
        streamAvg(arr, m);
 
// This code is contributed by todaysgaurav
</script>

Producción: 

Average of 1 numbers is 10.0
Average of 2 numbers is 15.0
Average of 3 numbers is 20.0
Average of 4 numbers is 25.0
Average of 5 numbers is 30.0
Average of 6 numbers is 35.0

Complejidad de tiempo: O(n)

Espacio Auxiliar: O(1)

Gracias a Abhijeet Deshpande por sugerir esta versión optimizada. 

Artículo relacionado:  
Programa para un promedio de un arreglo (Iterativo y Recursivo)

Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *