课堂小练习(complex类)
作者:互联网
定义一个复数类Complex,使得下面的代码能够工作:
Complex c1(3,5); //用复数3+5i初始化c1;
Compex c2=4.5; //用实数4.5初始化c2
c1.add(c2); //将c1与c2相加,结果保存在c1中
c1.show(); //将c1输出(这时的结果应该是7.5+5i)
cout<<c1.mod() //c1.mod()对c1进行取模运算
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 class Complex{ 6 public: 7 Complex (double real0,double imaginary0); 8 Complex (double real0); 9 Complex (Complex &C); 10 void add(Complex c2); 11 void show(); 12 double mod(); 13 private: 14 double real; 15 double imaginary; 16 double sreal; 17 double simaginary; 18 }; 19 20 Complex::Complex (double real0,double imaginary0):real(real0),imaginary(imaginary0){ 21 } 22 23 Complex::Complex (double real0):real(real0),imaginary(0){ 24 } 25 26 Complex::Complex(Complex &c3):real(c3.real),imaginary(c3.imaginary){ 27 } 28 29 void Complex::add(Complex c2){ 30 sreal=real+c2.real; 31 simaginary=imaginary+c2.imaginary; 32 } 33 34 void Complex::show(){ 35 cout<<sreal<<"+"<<simaginary<<"i"<<endl; 36 } 37 38 double Complex::mod(){ 39 double mod0; 40 mod0=sqrt(sreal*sreal+simaginary*simaginary); 41 return mod0; 42 } 43 44 int main(){ 45 Complex c1(3,5); 46 Complex c2(4.5); 47 Complex c3(c1); 48 c1.add(c2); 49 cout << "c1 + c2 = "; 50 c1.show(); 51 cout << "mod = "; 52 cout<<c1.mod()<<endl; 53 return 0; 54 }
运行截图
标签:real,double,练习,complex,Complex,c2,课堂,c1,imaginary 来源: https://www.cnblogs.com/dadadacy/p/10633987.html