C++ Complex::imag() 函数



C++ 的std::complex::imag() 函数用于获取复数的虚部。它与 complex 类模板一起使用,该模板表示和操作复数。它返回复数的虚部作为浮点数,而不修改对象本身。

语法

以下是 std::complex::imag() 函数的语法。

imag (const complex<T>& x); double imag (ArithmeticType x);

参数

  • x - 表示复数值。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

它返回复数 x 的虚部。

异常

示例 1

在下面的示例中,我们将考虑 imag() 函数的基本用法。

Open Compiler
#include <iostream> #include <complex> int main() { std::complex < double > x(1.0, 2.3); std::cout << "Imaginary part: " << x.imag() << std::endl; return 0; }

输出

以下是上述代码的输出:

Imaginary part: 2.3

示例 2

考虑以下示例,我们将使用带有默认虚部的 imag()。

Open Compiler
#include <iostream> #include <complex> int main() { std::complex < double > a(1.2); std::cout << "Imaginary part: " << a.imag() << std::endl; return 0; }

输出

如果我们运行上述代码,它将生成以下输出:

Imaginary part: 0

示例 3

让我们看下面的例子,我们将修改虚部。

Open Compiler
#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; }

输出

上述代码的输出如下:

Before Modification: 1.3
After Modification: 2.4
complex.htm
广告