#include <stdio.h> /* Input/Output Header */
#include <stdlib.h> /* Per la funzione malloc */
/* Maggioranza.c
Written by Piero Tofy 2005
http://www.pierotofy.it */
/* About Messages */
void ShowAbout(void){
printf("Calcolo dell'elemento di maggioranza by Piero Tofy 2005 http://www.pierotofy.it\n\n");
}
void GetElementCount(int *pInt){
do{
printf("Digita il numero di elementi da inserire (min. 3):");
}while(scanf("%d",pInt) != 1 || *pInt < 3);
}
int GetMajorValue(int iElementCount){
/* Se il numero è pari, il valore di maggioranza è pari alla metà,
altrimenti è pari alla metà più uno */
if ((iElementCount % 2) == 0) return iElementCount/2;
else return iElementCount/2+1;
}
void GetValues(double pElementArray[], int iElementCount){
unsigned short int c;
for (c = 0; c<iElementCount; c++){
do{
printf("Inserisci l'elemento n.%d: ",c
+1
);
}while(scanf("%lf",&pElementArray[c]) != 1);
}
}
int IsTheMajorValue(double dNumber, double pElementArray[], int iElementCount, int iMajorValue){
unsigned short int c;
int iElementMatchCount = 0;
for (c=0; c<iElementCount; c++)
if (pElementArray[c] == dNumber) iElementMatchCount++;
if (iElementMatchCount >= iMajorValue) return 1;
else return 0;
}
void CheckForAMajorValue(double pElementArray[], int iElementCount, int iMajorValue){
unsigned short int c;
for (c=0; c<iElementCount; c++){
if (IsTheMajorValue(pElementArray[c],pElementArray,iElementCount,iMajorValue)){
printf("E' stato trovato il numero di maggioranza (%lf).\n",pElementArray
[c
]);
return;
}
}
/* Se non è stato trovato il numero di maggioranza... */
printf("Non e' stato trovato un numero di maggioranza.\n");
}
/* Entry Point */
int main(void){
/* Dichiarazione delle variabili */
double *pElementArray = 0;
int iElementCount, iMajorValue;
/* Visualizza l'about */
ShowAbout();
/* Prende il numero di elementi */
GetElementCount(&iElementCount);
/* Alloca la memoria necessaria per l'array */
pElementArray = (double *)malloc(sizeof(double)*iElementCount);
/* Assengna il valore di maggioranza */
iMajorValue = GetMajorValue(iElementCount);
/* Raccoglie gli elementi */
GetValues(pElementArray,iElementCount);
/* Controlla l'esistenza di un numero di maggioranza */
CheckForAMajorValue(pElementArray,iElementCount,iMajorValue);
/* Esce dal programma */
exit(EXIT_SUCCESS);
}