Write a program to overload arithmetic minus operator for subtracting two complex numbers (use constructors also).
Question
Write a program to overload arithmetic minus operator for subtracting two complex numbers (use constructors also).
Solution
Sure, here is a Python program that overloads the arithmetic minus operator for subtracting two complex numbers using constructors:
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
# Overloading the '-' operator
def __sub__(self, other):
return Complex(self.real - other.real, self.imag - other.imag)
def __str__(self):
return f"{self.real} - {self.imag}i"
# Creating two complex numbers
c1 = Complex(3, 2)
c2 = Complex(1, 2)
# Subtracting two complex numbers using overloaded '-' operator
c3 = c1 - c2
print("The subtraction of two complex numbers is", c3)
In this program, we define a class Complex
to represent complex numbers. We define a constructor __init__
to initialize the real and imaginary parts of a complex number. We overload the -
operator by defining a method __sub__
that returns a new Complex
object representing the difference of two complex numbers. The __str__
method is used to represent the Complex
object as a string.
Similar Questions
Write a program overloading arithmetic operators to add two complex numbers using oops c++
Subtract the following complex numbers:(2 + 2i) - (14 + 16i)A.-12 + 18iB.12 + 18iC.12 - 14iD.-12 - 14iSUBMITarrow_backPREVIOUS
Subtract the following complex numbers:(11 - 9i) - (15 - 12i)A.-4 - 21iB.-4 + 3iC.4 + 3iD.4 - 21iSUBMITarrow_backPREVIOUS
Write a program to enter two numbers and print the arithmeticoperations like +,-,*,**, /, // and % using function
The operators ++ and -- are used to increment or decrement the variable value by ______.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.