halo
This commit is contained in:
parent
694f8ce9f4
commit
06e75a4a78
87
modus.c
Normal file
87
modus.c
Normal file
@ -0,0 +1,87 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
void erstelleZufallszahlen(int *array, int size);
|
||||
int vergleiche(const void *a, const void *b);
|
||||
int findeModus(int *array, int size);
|
||||
|
||||
int main() {
|
||||
int length = 0;
|
||||
int validInput = 0;
|
||||
|
||||
while (!validInput) {
|
||||
printf("Wieviele Zufallswerte (1..10000): ");
|
||||
scanf("%d", &length);
|
||||
while (getchar() != '\n'); // Eingabepuffer leeren
|
||||
if (length <= 0 || length > 10000) {
|
||||
printf("Ungueltige Eingabe. Bitte geben Sie eine Zahl zwischen 1 und 10000 ein.\n");
|
||||
} else {
|
||||
validInput = 1;
|
||||
}
|
||||
}
|
||||
|
||||
int randomnumbers[length]; // Array für die Zufallszahlen
|
||||
|
||||
// Zufallszahlengenerator initialisieren
|
||||
srand(time(NULL));
|
||||
|
||||
// Zufallszahlen erstellen
|
||||
erstelleZufallszahlen(randomnumbers, length);
|
||||
|
||||
// Zufallszahlen ausgeben
|
||||
printf("Die generierten Zufallszahlen sind:\n");
|
||||
for (int i = 0; i < length; i++) {
|
||||
printf("%d ", randomnumbers[i]);
|
||||
}
|
||||
|
||||
// Zufallszahlen sortieren
|
||||
qsort(randomnumbers, length, sizeof(int), vergleiche);
|
||||
|
||||
// Sortierte Zufallszahlen ausgeben
|
||||
printf("Die sortierten Zufallszahlen sind:\n");
|
||||
for (int i = 0; i < length; i++) {
|
||||
printf("%d ", randomnumbers[i]);
|
||||
}
|
||||
|
||||
// Modus berechnen
|
||||
int modus = findeModus(randomnumbers, length);
|
||||
printf("Der Modus der Zahlenreihe ist: %d\n", modus);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void erstelleZufallszahlen(int *array, int size) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
*(array + i) = rand() % 100 + 1; // Zufallszahl zwischen 1 und 100
|
||||
}
|
||||
}
|
||||
|
||||
int vergleiche(const void *a, const void *b) {
|
||||
return (*(int *)a - *(int *)b); // Vergleichsfunktion für qsort
|
||||
}
|
||||
|
||||
int findeModus(int *array, int size) {
|
||||
int modus = array[0];
|
||||
int maxCount = 1;
|
||||
int currentCount = 1;
|
||||
|
||||
for (int i = 1; i < size; i++) {
|
||||
if (array[i] == array[i - 1]) {
|
||||
currentCount++; // Gleiche Zahl gefunden, Zähler erhöhen
|
||||
} else {
|
||||
if (currentCount > maxCount) {
|
||||
maxCount = currentCount; // Neuer Modus gefunden
|
||||
modus = array[i - 1];
|
||||
}
|
||||
currentCount = 1; // Zähler zurücksetzen
|
||||
}
|
||||
}
|
||||
|
||||
// Letzte Zahl prüfen
|
||||
if (currentCount > maxCount) {
|
||||
modus = array[size - 1];
|
||||
}
|
||||
|
||||
return modus;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user