
345 views
C++ program to add two complex numbers using class
You can create a C++ program to add two complex numbers using a class to represent complex numbers. Here’s an example:
C++
#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) {
double resultReal = real + other.real;
double resultImag = imag + other.imag;
return Complex(resultReal, resultImag);
}
void display() {
std::cout << "Complex number: " << real << " + " << imag << "i" << std::endl;
}
};
int main() {
// Create two complex numbers
Complex num1(3.0, 4.0);
Complex num2(1.5, 2.5);
// Add the two complex numbers
Complex sum = num1 + num2;
// Display the result
num1.display();
num2.display();
sum.display();
return 0;
}In this program:
- We define a
Complexclass to represent complex numbers. The class has two private data members:realandimag, which represent the real and imaginary parts of the complex number. - The constructor
Complex(double r, double i)initializes the complex number with the given real and imaginary parts. - We overload the
+operator using theoperator+member function to add two complex numbers. The result is a new complex number. - The
displaymember function is used to display the complex number. - In the
mainfunction, we create twoComplexobjects (num1andnum2), initialize them with real and imaginary parts, and then add them together using the+operator. Finally, we display the original complex numbers and the result.
When you run this program, it will create two complex numbers, add them, and display the result:
Complex number: 3 + 4i
Complex number: 1.5 + 2.5i
Complex number: 4.5 + 6.5i