Created
November 13, 2019 04:16
-
-
Save parzibyte/656ba95156288946573837bc765c961d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Obtener media y mediana de arreglo en C | |
* Media: promedio | |
* Mediana: el elemento que se encuentra en el centro de una serie ordenada | |
* | |
* @author parzibyte | |
* @see https://parzibyte.me/blog | |
* */ | |
#include <stdio.h> | |
#include <stdlib.h> | |
int funcionQueCompara(const void *a, const void *b) { | |
// Castear a enteros | |
int aInt = *(int *) a; | |
int bInt = *(int *) b; | |
// Al restarlos, se debe obtener un número mayor, menor o igual a 0 | |
// Con esto ordenamos de manera ascendente | |
return bInt - aInt; | |
} | |
int main(void) { | |
int arreglo[] = {28, 11, 96, 21, 97, 6, 18, 13, 1, 19, 51}; | |
int tamanioElemento = sizeof arreglo[0]; | |
int longitud = sizeof arreglo / tamanioElemento; | |
// Obtener media | |
int sumatoria = 0; | |
for (int x = 0; x < longitud; x++) { | |
sumatoria += arreglo[x]; | |
} | |
float media = (float) sumatoria / (float) longitud; | |
// Ahora sumatoria | |
// Primero ordenamos el arreglo | |
qsort(arreglo, longitud, tamanioElemento, funcionQueCompara); | |
int mitad = longitud / 2; | |
int mediana; | |
// Después vemos si la longitud es par | |
if (longitud % 2 == 0) { | |
// Debemos promediar los valores del centro | |
mediana = (arreglo[mitad - 1] + arreglo[mitad]) / 2; | |
} else { | |
mediana = arreglo[mitad]; | |
} | |
printf("Imprimendo arreglo:\n"); | |
for (int x = 0; x < longitud; x++) { | |
printf("%d ", arreglo[x]); | |
} | |
printf("\nMediana: %d", mediana); | |
printf("\nMedia: %f", media); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment