Solution Review: Subtract Two Complex Numbers
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
Solution #
Press the RUN button and see the output!
Press + to interact
#include <iostream>using namespace std;// Structure to store complex numberstruct complex_number {// Store real part of complex numberdouble real;// Store imaginary part of complex numberdouble imaginary;};// Function subtractcomplex_number subtract(struct complex_number c1, struct complex_number c2) {// Declare a structure variablestruct complex_number c;// Subtract real partsc.real = c1.real - c2.real;// Subtract imaginary partsc.imaginary = c1.imaginary - c2.imaginary;// Return structure variablereturn c;}// Function print_complexvoid print_complex(struct complex_number c) {cout << c.real << " + ";cout << c.imaginary << " i ";cout << endl;}// Function mainint main() {// Declare structure variablesstruct complex_number c1, c2, c;// Initialize structure variable c1c1 = { -12.3, -67.4 };// Initialize structure variable c2c2 = { 34, 89 };// Print members of c1cout << "First complex number = " ;print_complex(c1);// Print members of c2cout << "Second complex number = " ;print_complex(c2);// Call subtract function and store its output in cc = subtract(c1, c2);// Print members of ccout << "First complex number - Second complex number = " ;print_complex(c);}
Explanation
struct complex_number
We ...