40 lines
1.2 KiB
C
40 lines
1.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <math.h>
|
|
#include "complex.h"
|
|
|
|
Complex* createComplex(double real, double imag) {
|
|
Complex* z = malloc(sizeof(Complex));
|
|
if (z != NULL) {
|
|
z->real = real;
|
|
z->imag = imag;
|
|
}
|
|
return z;
|
|
}
|
|
void freeComplex(Complex* z) {
|
|
free(z);
|
|
}
|
|
Complex* addComplex(const Complex* a, const Complex* b) {
|
|
return createComplex(a->real + b->real, a->imag + b->imag);
|
|
}
|
|
Complex* subtractComplex(const Complex* a, const Complex* b) {
|
|
return createComplex(a->real - b->real, a->imag - b->imag);
|
|
}
|
|
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);
|
|
}
|
|
Complex* divideComplex(const Complex* a, const Complex* b) {
|
|
double denom = b->real * b->real + b->imag * b->imag;
|
|
if (denom == 0.0) return NULL;
|
|
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);
|
|
}
|
|
void printComplex(const Complex* z) {
|
|
if (z)
|
|
printf("(%.3f + %.3fi)\n", z->real, z->imag);
|
|
else
|
|
printf("NULL (division durch 0?)\n");
|
|
} |