Test2
This commit is contained in:
parent
5024214330
commit
8b4a7b9150
90
kommahinzufügen.c
Normal file
90
kommahinzufügen.c
Normal file
@ -0,0 +1,90 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX 100
|
||||
|
||||
typedef struct {
|
||||
long vorkomma;
|
||||
long nachkomma;
|
||||
int nachkomma_stellen;
|
||||
} Kommazahl;
|
||||
|
||||
// Funktion zum Potenzieren (10^n)
|
||||
long potenz(int basis, int exponent) {
|
||||
long result = 1;
|
||||
for (int i = 0; i < exponent; i++) {
|
||||
result *= basis;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Funktion zum Aufteilen der Zahl in Vor- und Nachkommateil
|
||||
Kommazahl parseKommazahl(char *eingabe) {
|
||||
Kommazahl z = {0, 0, 0};
|
||||
char *komma = strchr(eingabe, ','); //Überprüfung ob Zahl ein Komma besitzt
|
||||
|
||||
if (komma) {
|
||||
*komma = '\0'; // 0 ersetzt Komma
|
||||
z.vorkomma = atol(eingabe); // Wandelt Vorkomma in Ganzzahl um
|
||||
char *nachkomma_str = komma + 1;
|
||||
z.nachkomma = atol(nachkomma_str); // Wandelt nachkomma in Ganzzahl um
|
||||
z.nachkomma_stellen = strlen(nachkomma_str);
|
||||
} else {
|
||||
z.vorkomma = atol(eingabe);
|
||||
z.nachkomma = 0;
|
||||
z.nachkomma_stellen = 0;
|
||||
}
|
||||
|
||||
return z;
|
||||
}
|
||||
|
||||
int main() {
|
||||
Kommazahl eingaben[MAX];
|
||||
int anzahl = 0;
|
||||
int max_nachkomma_stellen = 0;
|
||||
|
||||
printf("Gib Deine Kommazahlen ein (Abschluss mit Leerzeile)\n");
|
||||
|
||||
char zeile[100];
|
||||
while (fgets(zeile, sizeof(zeile), stdin)) {
|
||||
// Entferne Zeilenumbruch
|
||||
size_t len = strlen(zeile);
|
||||
if (len > 0 && zeile[len - 1] == '\n') zeile[len - 1] = '\0';
|
||||
if (strlen(zeile) == 0) break;
|
||||
|
||||
// Entferne Leerzeichen
|
||||
for (int i = 0; zeile[i]; i++) {
|
||||
if (zeile[i] == ' ') {
|
||||
memmove(&zeile[i], &zeile[i + 1], strlen(&zeile[i]));
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
Kommazahl k = parseKommazahl(zeile);
|
||||
eingaben[anzahl] = k;
|
||||
if (k.nachkomma_stellen > max_nachkomma_stellen)
|
||||
max_nachkomma_stellen = k.nachkomma_stellen;
|
||||
anzahl++;
|
||||
}
|
||||
|
||||
Kommazahl summe = {0, 0, max_nachkomma_stellen};
|
||||
|
||||
for (int i = 0; i < anzahl; i++) {
|
||||
Kommazahl z = eingaben[i];
|
||||
summe.vorkomma += z.vorkomma;
|
||||
|
||||
int faktor = potenz(10, max_nachkomma_stellen - z.nachkomma_stellen);
|
||||
summe.nachkomma += z.nachkomma * faktor;
|
||||
}
|
||||
|
||||
// Übertrag
|
||||
long übertrag = summe.nachkomma / potenz(10, max_nachkomma_stellen);
|
||||
summe.vorkomma += übertrag;
|
||||
summe.nachkomma = summe.nachkomma % potenz(10, max_nachkomma_stellen);
|
||||
|
||||
printf("= %ld,%0*ld\n", summe.vorkomma, max_nachkomma_stellen, summe.nachkomma);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user