Advertisement
RadioNurshat

Complex

Feb 10th, 2021
677
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. struct Complex {
  6.     double Re;
  7.     double Im;
  8. };
  9.  
  10. Complex NewComplex(double a, double b) {
  11.     Complex c;
  12.     c.Re = a;
  13.     c.Im = b;
  14.     return c;
  15. }
  16. double Module(Complex a) {
  17.     return sqrt(a.Re * a.Re + a.Im * a.Im);
  18. }
  19. double Angle(Complex a) {
  20.     return atan2(a.Im, a.Re);
  21. }
  22. Complex Add(Complex a, Complex b) {
  23.     return NewComplex(a.Re + b.Re, a.Im + b.Im);
  24. }
  25. Complex Sub(Complex a, Complex b) {
  26.     return NewComplex(a.Re - b.Re, a.Im - b.Im);
  27. }
  28. Complex Mult(Complex a, Complex b) {
  29.     return NewComplex(a.Re * b.Re - a.Im * b.Im, a.Re * b.Im + a.Im * b.Re);
  30. }
  31. Complex Divide(Complex a, Complex b) {
  32.     return NewComplex((a.Re * b.Re + a.Im * b.Im) / (b.Im * b.Im + b.Re * b.Re), (b.Re * a.Im - a.Re * b.Im) / (b.Im * b.Im + b.Re * b.Re));
  33. }
  34. vector<Complex> Root(Complex a, int n) {
  35.     vector<Complex> roots;
  36.     double r = Module(a);
  37.     double fi = Angle(a);
  38.     for (int i = 0; i < n; i++) {
  39.         Complex Root = NewComplex(pow(r, 1.0 / n) * cos((fi + 2 * 3.14 * i) / n), pow(r, 1.0 / n) * sin((fi + 2 * 3.14 * i) / n));
  40.         roots.push_back(Root);
  41.     }
  42.     return roots;
  43. }
  44. Complex Power(Complex a, int n) {
  45.     return NewComplex(pow(Module(a), n) * cos(n * Angle(a)), pow(Module(a), n) * sin(n * Angle(a)));
  46. }
  47. string ComplexToString(Complex a) {
  48.     string out;
  49.     out += to_string(a.Re);
  50.     out += ((a.Im >= 0) ? "+" : "-");
  51.     out += to_string(abs(a.Im))+"i";
  52.     return out;
  53. }
  54. int main()
  55. {
  56.     setlocale(0, "ru");
  57.     Complex a = NewComplex(1, 5);
  58.     Complex b = NewComplex(4, 3);
  59.     cout << "a: " << ComplexToString(a) << endl;
  60.     cout << "b: " << ComplexToString(b) << endl;
  61.     cout << "Сложение: " << ComplexToString(Add(a, b)) << endl;
  62.     cout << "Вычитание: " << ComplexToString(Sub(a, b)) << endl;
  63.     cout << "Произведение: " << ComplexToString(Mult(a, b)) << endl;
  64.     cout << "Деление: " << ComplexToString(Divide(a, b)) << endl;
  65.     cout << "3 степень: " << ComplexToString(Power(a, 3)) << endl;
  66.     cout << "Корень 3 степени: " << endl;
  67.     vector<Complex> roots = Root(a, 3);
  68.     for (int i = 0; i < 3; i++) {
  69.         cout << i << ": " << ComplexToString(roots[i]) << endl;
  70.     }
  71. }
  72.  
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement