Modalwert in C programmieren?

2 Antworten

int modal(int mod[], size_t n, int *modalwert){
    int hzahl = mod[0]; // Zahl die am öfftesten 
                                    // vorkommt
    int hanz = 0; // Anzahl die am höchsten ist
    int zahl[n]; // Zahlen die gesucht werden 
    int anz[n]; // Anzahl wie oft eine Zahl vorkommt
    int i,j;   // Zählervariablen
    for(j=0; j < (int)n; j++){   
           anz[j]=0;    
           if(!kamvor(zahl, n, mod[j])) zahl[j] = mod[j];  
                else continue;    
          for(i = 0; i < (int)n; i++)
                if(zahl[j] == mod[i]) anz[j]++;      
          if(anz[j] > hanz){
                         hanz = anz[j];     
                         hzahl = zahl[j];
           } 
     }  // Überprüfen ob die größte Anzahl nur eimal
        // vorkommt 
  
 int vork = 0; // Zählt mit wie oft die größte Anzahl 
                      // vorkommt
 for(i = 0; i < (int)n; i++){
         if(anz[i]==0)     continue;
          if(anz[i] == hanz){
                vork++; 
                if(vork == 2) return 0;         
         }
     }
   *modalwert = hzahl; 
   return 1; 
 } 
 
int kamvor(int zahlen[], size_t n, int zahl){ 
 	  int i;
 	  for(i=0; i < (int)n;i++)if(zahlen[i] == zahl) 
                              return 0;    
 	 return 1;
 	}

al den Code etwas geordneter

Woher ich das weiß:eigene Erfahrung – Hobby und teilweise beruflich

Was ich nicht verstehe:

if(!kamvor(zahl, n, mod[j])) zahl[j] = mod[j];  
else continue; 

Hier ist zahl noch gar nicht besetzt bzw. zufällig! Denn Du suchst in kamvor (der Name müsste eigentlich heißen "kamnichtvor") bis n, und Du füllst zahl[] erst noch auf! ==> undefined behavior!

Es muss heißen !kamvor(zahl, (size_t)j, mod[j])

Woher ich das weiß:eigene Erfahrung – Hobby und teilweise beruflich