Search code examples
c++complex-numbers

How to use Complex numbers in Class/Object C++


Im strugling to implement complex numbers into my code. When I compile it gives me random numbers. It should use imaginary number i = sqrt(-1). It should output realPart + imaginaryPart * i.

#include <iostream>
#include <complex>
using namespace std;

class Complex
{
private:
    double i;
    complex<double> imaginarypart = i*sqrt(1);
    double realpart;
public:
    void seti(double a1) {
        i = a1;
    }
    void setrealpart(double a2) {
        realpart = a2;
    }
    void printwhole() {
        cout << realpart + imaginarypart;
    }
};

int main()
{
    double a, b;
    cout << "Enter your realpart" << endl;
    cin >> a;
    cout << "Enter your imaginarypart " << endl;
    cin >> b;

    Complex num1;
    num1.seti(b);
    num1.setrealpart(a);
    cout << endl;
    num1.printwhole();
}

Solution

  • The point is that an the type double cannot store imaginary values.
    Yet you try to do so, e.g. with sqrt(1); (though you probably meant -1).
    The complex<double> is indeed able to store imaginary values, but on the one hand it won't work by assigning the product of the non-initialised i with 1 and on the other hand you seem to try to implement complex numbers yourself. Using the provided complex standard type somewhat defeats that. If you use it, then you just need to learn outputting it in the format you want, instead of doing all the implementation work.

    Lets assume that you are more interested in getting it done yourself first.
    What you need to do is to always represent complex numbers as two numbers.
    I hence propose to change your code likes this.

    #include <iostream>
    using namespace std;
    
    class Complex
    {
    private:
        /* double i; Won't work, it cannot store imaginary values. */
        double imaginarypart;
        double realpart;
    public:
        void setimaginarypart(double a1) {
            imaginarypart = a1;
        }
        void setrealpart(double a2) {
            realpart = a2;
        }
        void printwhole() {
            cout << realpart << '+' <<  imaginarypart << 'i'; // To get the output you want.
        }
    };
    
    int main()
    {
        double a, b;
        cout << "Enter your realpart" << endl;
        cin >> a;
        cout << "Enter your imaginarypart " << endl;
        cin >> b;
    
        Complex num1;
        num1.setimaginarypart(b);
        num1.setrealpart(a);
        cout << endl;
        num1.printwhole();
    }
    

    Alternatively use existing solutions (e.g. std::complex), instead of trying to program one yourself. Outputting them in the shape you want (r+i*I) does not require to implement the whole thing yourself.
    Have a look at https://en.cppreference.com/w/cpp/numeric/complex to learn about what it offers.