Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct complex number basic arithmetics
// t11e03.complexnumbers.cpp
// juanfc 2022-01-16
//
#include <iostream>
using namespace std;
struct TComp {
float re, im;
};
TComp sumComp(TComp a, TComp b);
TComp subComp(TComp a, TComp b);
TComp mulComp(TComp a, TComp b);
TComp divComp(TComp a, TComp b);
void printComp(TComp a);
int main()
{
TComp w = {2, 1};
TComp z = {4, 3};
printComp(sumComp(z, w));
printComp(subComp(z, w));
printComp(mulComp(z, w));
printComp(divComp(z, w));
return 0;
}
TComp sumComp(TComp a, TComp b)
{
return (TComp){a.re+b.re, a.im+b.im};
}
TComp subComp(TComp a, TComp b)
{
return (TComp){a.re-b.re, a.im-b.im};
}
TComp mulComp(TComp a, TComp b)
{
return (TComp){a.re*b.re-a.im*b.im,
a.re*b.im+a.im*b.re};
}
float mod(TComp a);
TComp divComp(TComp a, TComp b)
{
float m = mod(b);
return (TComp){(a.re*b.re+a.im*b.im)/m,
(a.re*b.im-a.im*b.re)/m};
}
float mod(TComp a)
{
return a.re*a.re+a.im*a.im;
}
void printComp(TComp a)
{
if (a.im > 0)
cout << a.re << " + " << a.im << "i" << endl;
else if (a.im < 0)
cout << a.re << " - " << -a.im << "i"<< endl;
else
cout << a.re << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment