C++程序:获取给定复数的虚部
现代科学很大程度上依赖于复数的概念,该概念最初形成于17世纪早期。复数的公式为 a + ib,其中 a 和 b 是实数值。已知复数有两个部分:实部 (a) 和虚部 (ib)。i 或 iota 的值为 √-1。C++ 中的 complex 类是一个用于表示复数的类。C++ 中的 complex 类可以表示和控制多个复数运算。我们来看一下如何表示和显示复数。
imag() 成员函数
如前所述,复数有两个部分,实部和虚部。要显示实部,我们使用 real() 函数,而 imag() 函数用于显示给定复数的虚部。在下面的示例中,我们创建一个复数对象,对其进行初始化,然后分别显示该数的实部和虚部。
语法
//displaying the imaginary part only complex<double> c; cout << imag(c) << endl;
算法
创建一个新的复数对象。
使用“a + ib”表示法为对象赋值。
使用 imag() 函数显示复数值的虚部。
示例
#include <iostream>
#include <complex>
using namespace std;
//displays the imaginary part of the complex number
void display(complex <double> c){
cout << "The imaginary part of the complex number is: ";
cout << imag(c) << endl;
}
//initializing the complex number
complex<double> solve( double real, double img ){
complex<double> cno(real, img);
return cno;
}
int main(){
complex<double> cno = 10.0 + 11i;
//displaying the complex number
cout << "The complex number is: " << real(cno) << '+' << imag(cno) << 'i' << endl;
display(cno);
return 0;
}
输出
The complex number is: 10+11i The imaginary part of the complex number is: 11
需要注意的是,imag() 函数仅接受复数作为输入,并返回所提供复数的虚部。输出值是复数对象的模板参数。
结论
在广泛的科学领域中,需要复数来进行许多不同的运算。C++ complex 类(它是 <complex> 头文件的一部分)提供了一个用于表示复数的接口。complex 类支持所有复数运算,包括加法、减法、乘法、共轭、范数等等。正如我们本文刚刚介绍的那样,可以使用常规数值轻松创建复数。务必记住,在表示复数时,必须同时考虑数的实部和虚部。否则,可能会出现一些问题。程序员必须确保不会混淆 real() 和 imag() 函数,否则值将被反转。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP