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