C++程式將數字轉換為複數
C++ 中的複數可以在標頭檔案 <complex> 中找到,它使開發人員能夠表示和操作複數。複數具有 a + ib 的形式,其中 'a' 被稱為複數的實部,'ib' 是複數的虛部。虛部用字母 'i' 表示,其值為“iota”,等於 -1。複數在許多程式中非常重要,因為它們被用於許多數學和科學過程中。我們來看看如何在 C++ 中表示覆數以及如何將普通數字轉換為複數。
使用建構函式
我們可以使用 complex 類的建構函式來構造一個複數。要建立複數,我們必須將數字的實部和虛部作為引數傳遞給建構函式。
語法
double value1 = <double value>; double value2 = <double value>; complex <double> cno(value1, value2);
演算法
在兩個數值變數中輸入。
將這兩個變數傳遞給複數的建構函式。
顯示覆數。
示例
#include <iostream> #include <complex> using namespace std; //displays the complex number supplied void display(complex <double> c){ cout << "The complex number is: "; cout << real(c) << '+' << imag(c) << 'i' << endl; } int main(){ //the real and the imaginary values are represented as double values double value1 = 2.05; double value2 = 3; //creating the complex number complex <double> cno(value1, value2); display(cno); return 0; }
輸出
The complex number is: 2.05+3i
我們將複數的變數型別設定為 double,但任何數值資料型別都可以代替它。
使用賦值運算子
我們還可以使用賦值運算子將實部和虛部值賦給複數。但是,要進行賦值,我們必須以“a + bi”的形式賦值,其中 a 和 b 是數值。實部“a”必須用小數點書寫;如果數字是整數,我們用零填充小數點後的部分。例如,我們必須將 5 寫成 5.0。
語法
//the real and imaginary parts have to be assigned as it is complex <double> cno = 5.0 + 2i;
演算法
獲取一個新的複數物件。
使用“a. + ib”表示法為物件賦值。
顯示覆數值。
示例
#include <iostream> #include <complex> using namespace std; //displays the complex number supplied void display(complex <double> c){ cout << "The complex number is: "; cout << real(c) << '+' << imag(c) << 'i' << endl; } int main(){ //creating the complex number complex <double> cno = 5.0 + 2i; display(cno); return 0; }
輸出
The complex number is: 5+2i
顯示覆數
複數的實部和虛部必須使用“real()”和“imag()”函式以不同的方式顯示。“real()”函式顯示覆數的實部,而“imag()”函式表示複數的虛部。我們來看一個例子。
語法
//displaying in the a + ib format cout << real(c) << '+' << imag(c) << 'i' << endl;
演算法
獲取一個新的複數物件。
使用“a. + ib”表示法為物件賦值。
顯示覆數值。
示例
#include <iostream> #include <complex> using namespace std; //displays the complex number supplied void display(complex <double> c){ cout << "The complex number is: "; cout << real(c) << '+' << imag(c) << 'i' << endl; } int main(){ //creating the complex number complex <double> cno = 7.0 + 9i; display(cno); return 0; }
輸出
The complex number is: 7+9i
結論
複數在各個科學領域的各種操作中非常需要。C++ 中的 complex 類提供了表示複數的介面。complex 類支援對複數的所有型別的操作,例如加法、減法、乘法、共軛、範數等等。正如我們在本文中討論的那樣,從普通數值到複數的轉換非常容易。
廣告