C++ 中的複數


在本節中,我們將瞭解如何在 C++ 中建立和使用複數。我們可以在 C++ 中建立複數類,其中可以將複數的實部和虛部作為成員元素保留下來。有些成員函式用於處理該類。

在此示例中,我們建立了一個特定型別的複數類,有一個函式可以將複數顯示為正確的格式。還有兩種附加的方法可用於新增和減去兩個複數等。

範例

 Flex Demo

#include<iostream>
using namespace std;
class complex {
   int real, img;
   public:
      complex() {
         //default constructor to initialize complex number to 0+0i
         real = 0; img = 0;
      }
      complex(int r, int i) {
         //parameterized constructor to initialize complex number.
         real = r; img = i;
      }
      void set();
      void get();
      void display();
      friend complex add(complex, complex);
      friend complex sub(complex, complex);
};
void complex::set() {
   cout << "Enter Real part: ";
   cin >> real;
   cout << "Enter Imaginary Part: ";
   cin >> img;
}
void complex::get() {
   cout << "The complex number is: "<< real << "+" << img << "i" << endl;
}
void complex::display() {
   if(img < 0)
      if(img == -1)
         cout << "The complex number is: "<< real << "-i" << endl;
      else
         cout << "The complex number is: "<< real << img << "i" << endl;
      else
         if(img == 1)
            cout << "The complex number is: "<< real << " + i"<< endl;
         else
            cout << "The complex number is: "<< real << " + " << img << "i" <<
   endl;
}
complex add(complex c1, complex c2) {
   complex res;
   res.real = c1.real + c2.real;//addition for real part
   res.img = c1.img + c2.img;//addition for imaginary part
   return res;//the result after addition
}
complex sub(complex c1, complex c2) {
   complex res;
   res.real = c1.real - c2.real;//subtraction for real part
   res.img = c1.img - c2.img;//subtraction for imaginary part
   return res;//the result after subtraction
}
main() {
   complex n1(3, 2), n2(4, -3);
   complex result;
   result = add(n1,n2);
   result.display();
   result = sub(n1,n2);
   result.display();
}

輸出

The complex number is: 7-i
The complex number is: -1 + 5i

更新於:2019 年 7 月 30 日

9K+ 次瀏覽

開啟您的 職業生涯

完成課程取得認證

開始吧
廣告