/*
實驗内容:【任務3】閱讀P314的例10.1(電子版的在平台上見txt檔案)。該例實作了一個複數類,但是美中不足的是,複數類的實部和虛部都固定是double型的。可以通過模闆類的技術手段,設計Complex,使實部和虛部的類型為定義對象時用的實際類型。
(1)要求類成員函數在類外定義。
(2)在此基礎上,再實作減法、乘法和除法
* 程式的版權和版本聲明部分
* Copyright (c) 2011, 煙台大學計算機學院學生
* All rights reserved.
* 檔案名稱: 複數的加減乘除
* 作 者: 薛廣晨
* 完成日期: 2012 年 4 月 3 日
* 版 本号: x1.0
* 對任務及求解方法的描述部分
* 輸入描述:練習使用類模闆
* 程式頭部的注釋結束(此處也删除了斜杠)
*/
#include <iostream>
using namespace std;
template<class numtype>
class Complex
{
public:
Complex( ){real = 0; imag = 0;}
Complex(numtype r, numtype i){real = r; imag = i;}
Complex complex_add(Complex &c2); //加法
Complex complex_cut(Complex &c2);//減法
Complex complex_multiply(Complex &c2);//乘法
Complex complex_divide(Complex &c2);//除法
void display( );
private:
numtype real;
numtype imag;
};
template<class numtype>
Complex<numtype> Complex<numtype> :: complex_add(Complex &c2)
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype> :: complex_cut(Complex &c2)
{
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype> :: complex_multiply(Complex &c2)
{
Complex c;
c.real = real * c2.real - imag * c2.imag;
c.imag = imag * c2.real + real * c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype> :: complex_divide(Complex &c2)
{
Complex c;
c.real = (real * c2.real + imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
c.imag = (imag * c2.real - real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
return c;
}
template<class numtype>
void Complex<numtype> :: display( )
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main( )
{ Complex<int> c1(3, 4), c2(5, -10), c3;
c3 = c1.complex_add(c2);
cout << "c1+c2=";
c3.display( );
Complex<double> c4(3.1, 4.4), c5(5.34, -10.21), c6, c7;
c6 = c4.complex_add(c5);
cout << "c4 + c5=";
c6.display( );
c7 = c4.complex_cut(c5);
cout << "c4 - c5=";
c7.display( );
Complex<double> c8(5.1, 3.2), c9(4.2, -2), d1, d2;
d1 = c8.complex_multiply(c9);
d2 = c8.complex_divide(c9);
cout << "c8 x c9 =";
d1.display( );
cout << "c8 ÷ c9 =";
d2.display( );
system("pause");
return 0;
}
第七周 任務三(完整版) 複數的加減乘除