Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a function which returns complex in C++?

I am trying to do numerical calculations with C++. Here is the sample code

#include <complex> 
using namespace std;


complex<double> complexDo(float a, float b){

    return (a+b,a-b);
}

int main(){

    cout << "complexDo="<<complexDo(3,2) <<'\n';
    return 0;
}

The terminal will show after compiling

complexDo=(1,0)

But I expect to appear like (5, 1), and what is the problem here? Or this way of writing is not valid in C++?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The expression (a+b,a-b) is equivalent to (a-b) because it’s just a parenthesized use of the common comma expression.

To create an object you must use curly-braces {} as in

return {a+b,a-b};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading