Skip to content

Instantly share code, notes, and snippets.

@jpolivra
Created October 20, 2023 21:08
Show Gist options
  • Save jpolivra/da58eca4214ddf893b6ede5c51ea48fa to your computer and use it in GitHub Desktop.
Save jpolivra/da58eca4214ddf893b6ede5c51ea48fa to your computer and use it in GitHub Desktop.
Make a program that read two complex numbers and perform math basics operations around them (sum, subtract, multiply and divide).
using System;
namespace abstract_data_types;
class Program
{
class Complex {
private double _PReal;
private double _PImag;
public void Read()
{
Console.WriteLine("Register complex number:");
Console.Write("PReal:");
_PReal = double.Parse(Console.ReadLine());
Console.Write("PImag:");
_PImag = double.Parse(Console.ReadLine());
Console.WriteLine("Complex number successfully registered!");
}
public void Sum(Complex a, Complex b)
{
_PReal = a._PReal + b._PReal;
_PImag = a._PImag + b._PImag;
}
public void Subtract(Complex a, Complex b)
{
_PReal = a._PReal - b._PReal;
_PImag = a._PImag - b._PImag;
}
public void Multiply(Complex a, Complex b)
{
_PReal = a._PReal * b._PReal - a._PImag * b._PImag;
_PImag = a._PReal * b._PImag + a._PImag * b._PReal;
}
public void Divide(Complex a, Complex b)
{
Complex Aux = new Complex();
b.FindConjugate();
Aux.Multiply(a, b);
_PReal = Aux._PReal / (Math.Pow(b._PReal, 2) + Math.Pow(b._PImag, 2));
_PImag = Aux._PImag / (Math.Pow(b._PReal, 2) + Math.Pow(b._PImag, 2));
}
private void FindConjugate()
{
_PImag = -_PImag;
}
public void DisplayComplex(string beforeSuffix)
{
Console.Write($"\n{beforeSuffix}");
Console.WriteLine($"{_PReal:F2}{(_PImag >= 0 ? " + " : " - ")}{Math.Abs(_PImag):F2}i");
Console.ReadKey();
}
}
static void Main(string[] args)
{
// Initialize complex numbers
Complex a = new Complex();
Complex b = new Complex();
a.Read();
b.Read();
Complex Sum = new Complex();
Complex Subtract = new Complex();
Complex Multiply = new Complex();
Complex Divide = new Complex();
Sum.Sum(a, b);
Subtract.Subtract(a, b);
Multiply.Multiply(a, b);
Divide.Divide(a, b);
Console.WriteLine("\n");
Sum.DisplayComplex("Sum: ");
Subtract.DisplayComplex("Subtract: ");
Multiply.DisplayComplex("Multiply: ");
Divide.DisplayComplex("Divide: ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment