complex类
作者:互联网
#include<iostream> #include<cmath> using namespace std; class Complex { public: Complex(double x, double y) { real = x;imaginary = y; } Complex(double x) { real = x;imaginary = 0; } Complex(Complex &t) {real = t.real;imaginary = t.imaginary;} void add(Complex &t); void show(); double mod(); private: double real, imaginary; }; void Complex::add(Complex &t) { real = t.real + real; imaginary = t.imaginary + imaginary; } void Complex::show() { if(imaginary > 0) cout << real << "+" << imaginary << "i" << endl; else if (imaginary < 0) cout << real << imaginary << "i" << endl; else cout << real << endl; //虚数为0或小于0时,改变表达方式。避免出现类似a+-bi的情况。 } double Complex::mod() { return sqrt(real * real + imaginary * imaginary); } int main() { Complex c1(3, 5); c1.show(); Complex c2 = 4.5; c2.show(); Complex c3(c1); Complex c4(3, -5); c4.show(); c1.add(c2); c1.show(); cout << c1.mod() << endl; return 0; }
标签:real,show,double,void,complex,Complex,imaginary 来源: https://www.cnblogs.com/cwj0505/p/10629125.html