C++ Complex::imag() function
The C++ std::complex::imag() function is used to retrieve the imaginary part of a complex number. It works with the complex class template, which represents and manipulates complex numbers. It returns the imaginary component of the complex number as a floating point value, without modifying the object.
Syntax
Following is the syntax for std::complex::imag() function.
imag (const complex<T>& x); double imag (ArithmeticType x);
Parameters
- x − It indicates the complex value.
Return Value
It returns the imaginary part of the complex number x.
Exceptions
none
Example 1
In the following example, we are going to consider the basic usage of imag() function.
#include <iostream>
#include <complex>
int main() {
std::complex < double > x(1.0, 2.3);
std::cout << "Imaginary part: " << x.imag() << std::endl;
return 0;
}
Output
Following is the output of the above code −
Imaginary part: 2.3
Example 2
Consider the following example, where we are going to use the imag() with the default imaginary part.
#include <iostream>
#include <complex>
int main() {
std::complex < double > a(1.2);
std::cout << "Imaginary part: " << a.imag() << std::endl;
return 0;
}
Output
If we run the above code it will generate the following output −
Imaginary part: 0
Example 3
Let's look at the following example, where we are going to modify the imaginary part.
#include <iostream>
#include <complex>
int main() {
std::complex < float > a(1.2, 1.3);
std::cout << "Before Modification: " << a.imag() << std::endl;
a = std::complex < float > (a.real(), 2.4);
std::cout << "After Modification: " << a.imag() << std::endl;
return 0;
}
Output
Output of the above code is as follows −
Before Modification: 1.3 After Modification: 2.4