Info2P5/complex.c
2025-05-23 07:32:31 +02:00

54 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "complex.h"
// Erzeugt eine neue komplexe Zahl und gibt einen Zeiger darauf zurück
Complex* createComplex(double real, double imag) {
Complex* z = malloc(sizeof(Complex)); // Speicher reservieren
if (z != NULL) {
z->real = real;
z->imag = imag;
}
return z;
}
// Gibt den Speicher einer komplexen Zahl frei
void freeComplex(Complex* z) {
free(z);
}
// Addiert zwei komplexe Zahlen und gibt das Ergebnis als neue Zahl zurück
Complex* addComplex(const Complex* a, const Complex* b) {
return createComplex(a->real + b->real, a->imag + b->imag);
}
// Subtrahiert zwei komplexe Zahlen und gibt das Ergebnis als neue Zahl zurück
Complex* subtractComplex(const Complex* a, const Complex* b) {
return createComplex(a->real - b->real, a->imag - b->imag);
}
// Multipliziert zwei komplexe Zahlen und gibt das Ergebnis als neue Zahl zurück
Complex* multiplyComplex(const Complex* a, const Complex* b) {
double real = a->real * b->real - a->imag * b->imag;
double imag = a->real * b->imag + a->imag * b->real;
return createComplex(real, imag);
}
// Dividiert zwei komplexe Zahlen und gibt das Ergebnis als neue Zahl zurück
Complex* divideComplex(const Complex* a, const Complex* b) {
double denom = b->real * b->real + b->imag * b->imag; // Nenner berechnen
if (denom == 0.0) return NULL; // Division durch 0 abfangen
double real = (a->real * b->real + a->imag * b->imag) / denom;
double imag = (a->imag * b->real - a->real * b->imag) / denom;
return createComplex(real, imag);
}
// Gibt eine komplexe Zahl in der Form (a + bi) aus
void printComplex(const Complex* z) {
if (z)
printf("(%.3f + %.3fi)\n", z->real, z->imag);
else
printf("NULL -> Division durch 0 nicht möglich\n");
}