C++程式:初始化和列印複數


複數是現代科學中一個非常基礎的概念,最早在17世紀初被提出。複數的形式為 a + ib,其中 a 和 b 是實數。a 稱為複數的實部,ib 稱為複數的虛部。在 C++ 中,有一個類可以表示複數,即 complex 類。C++ 中的 complex 類可以表示和操作複數的各種運算。我們來看一下如何表示、初始化和顯示覆數。

使用類建構函式進行初始化

要使用 complex 類,我們必須匯入 complex 庫,可以使用 #include 語句匯入或包含。下面描述了 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;
}

//initializing the complex number
complex<double> solve( double real, double img ){
   complex<double> cno(real, img);
   return cno;
}
int main(){

   //the real and the imaginary values are represented as double values
   double v1 = 10;
   double v2 = 7;

   //creating and displaying the complex number
   display(solve(v1, v2));
   return 0;
}

輸出

The complex number is: 10+7i

可以將任何數值資料型別用於複數變數的當前型別(double)代替。

使用賦值運算子進行初始化

我們也可以使用賦值運算子將實部和虛部賦值給複數。但是,要這樣做,我們必須提供“a + ib”型別的數字,其中“a”和“b”都是數值。如果數字是整數,則會在小數點後新增零。編寫實部“a”時必須使用小數點。例如,10 必須寫成 10.0。

語法

//the real and imaginary parts have to be assigned as it is
complex <double> cno = 15.0 + 6i;

演算法

  • 建立一個新的複數物件。

  • 使用“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(){
   
   //initializing a complex number object
   complex <double> cno = 15. + 6i;
   
   //displaying the complex number
   display(cno);
   return 0;
}

輸出

The complex number is: 15+6i

顯示覆數

使用“real()”和“imag()”函式,分別顯示覆數的實部和虛部。“real()”函式顯示覆數的實部,“imag()”函式顯示覆數的虛部。這是一個示例。

語法

//displaying in the a + ib format
complex<double> c;
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;
}
//initializing the complex number
complex<double> solve( double real, double img ){
   complex<double> cno(real, img);
   return cno;
}
int main(){
//the real and the imaginary values are represented as double values
   double v1 = 3;
   double v2 = 4;
//creating and displaying the complex number
   display(solve(v1, v2));
   return 0;
}

輸出

The complex number is: 3+4i

結論

複數在廣泛的科學領域中許多不同的程式中是必需的。C++ complex 類(包含在 header 中)提供了一個表示複數的介面。complex 類支援複數的所有運算,包括加法、減法、乘法、共軛、範數以及許多其他運算。正如我們在這篇文章中已經討論過的,將常規數值轉換為複數並不太難。我們需要注意的是,在顯示覆數時,必須注意數字的實部和虛部,否則可能會在程式中產生一些錯誤。

更新於:2022年12月7日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.