In: Computer Science
Modify the Complex structure in the notes and create a method that returns the complex conjugate.
// Structure Method Notes C++
#include
using namespace std;
// Object Definition
struct Complex {
// Data members that define a complex number a +
bi
double a, b;
// function within a data structure = METHOD
// functions specific to this type of object.
void printComplex(void);
};
int main(void) {
int size = 3;
// Declare three Complex objects and intitialize
the data members.
// In other words, instantiate 3 complex
objects.
Complex z1 = { 3,4 };
Complex z2 = { 5,0 };
Complex z3;
z3.a = 6;
z3.b = -8;
// Use the given method to print the three
objects.
// Need three function calls.
z1.printComplex();
z2.printComplex();
z3.printComplex();
// In class we will create a function that calculates
and returns
// the distance from the origin.
// If time... change to an array of 3 Complex objects.
return(0);
}
//Function Implementations
// use the scope-resolution operator ( :: ) to tie the function to
the object definition
void Complex::printComplex(void) {
if (b >= 0)
cout << a << " + "
<< b << "i" << endl;
else
cout << a << " - "
<< -1 * b << "i" << endl;
}
Code:
// Structure Method Notes C++
#include <iostream>
using namespace std;
// Object Definition
struct Complex {
// Data members that define a complex number a + bi
double a, b;
// function within a data structure = METHOD
// functions specific to this type of object.
void printComplex(void);
// function to return complex conjugate
Complex complexConjugate(void);
};
int main(void) {
int size = 3;
// Declare three Complex objects and intitialize the data members.
// In other words, instantiate 3 complex objects.
Complex z1 = { 3,4 };
Complex z2 = { 5,0 };
Complex z3;
z3.a = 6;
z3.b = -8;
// Use the given method to print the three objects.
// Need three function calls.
z1.printComplex();
z2.printComplex();
z3.printComplex();
// check out complex conjugate
cout<<"Printing Complex Conjugate:"<<endl;
Complex z_1 = z1.complexConjugate();
Complex z_2 = z2.complexConjugate();
Complex z_3 = z3.complexConjugate();
// display results
z_1.printComplex();
z_2.printComplex();
z_3.printComplex();
return(0);
}
//Function Implementations
// use the scope-resolution operator ( :: ) to tie the function to the object definition
void Complex::printComplex(void) {
if (b >= 0)
cout << a << " + " << b << "i" << endl;
else
cout << a << " - " << -1 * b << "i" << endl;
}
// function to return complex Conjugate
Complex Complex::complexConjugate(void){
Complex x;
x.a = a;
x.b = b;
if(x.b != 0){ // this is done because, if b is 0, then output would be like a + -0i
x.b = -1*x.b;
}
return x;
}
Code Screenshot:
Code output:
=================
Please refer to the code and screenshot added above.
Please upvote.