建立一個複數類Complex,進行復數的加、減運算。編寫主函式進行測試。
阿新 • • 發佈:2019-02-01
數具有如下形式:
realPart+imaginaryPart*i。
用double變量表示該類的private資料:realPart(實部)和imaginaryPart(虛部)。提供一個無參建構函式,使realPart和imaginaryPart均為0;一個有參建構函式,使物件在宣告時就得以初始化。提供public的成員函式:
① Complex ComPlexAdd(Complex &a);//完成當前物件與引用物件a的複數相加
//即兩個物件的實部相加,虛部相加
//將計算結果返回
② Complex ComPlexSub(Complex &b);//完成當前物件與引用物件a的複數相減
③ void Print(); //輸出複數
#include<iostream> using namespace std; class Complex { private: double realPart; double imaginaryPart; public: Complex() { realPart=0; imaginaryPart=0; } Complex(double a,double b) { realPart=a; imaginaryPart=b; } Complex ComPlexAdd(Complex &a) { realPart+=a.realPart ; imaginaryPart+=a.imaginaryPart; return Complex(realPart,imaginaryPart); } Complex ComPlexSub(Complex &b) { realPart-=b.realPart ; imaginaryPart-=b.imaginaryPart; return Complex(realPart,imaginaryPart); } void Print() { cout<<realPart<<"+"<<imaginaryPart<<"i"<<endl; } }; int main() { Complex a = Complex(); Complex b = Complex(3,4); Complex c = Complex(2,3); a.Print(); a.ComPlexAdd(b); a.Print(); a.ComPlexSub(c); a.Print(); return 0; }