在本节中,我们将看到如何在C ++中创建和使用复数。我们可以在C ++中创建复数类,该类可以将复数的实部和虚部作为成员元素保存。将有一些用于处理此类的成员函数。
在此示例中,我们将创建一个复杂类型类,该函数将复杂数字显示为正确的格式。两种另外的方法来加减两个复数,等等。
#include<iostream> using namespace std; class complex{ int real, img; public: complex(){ //默认构造函数将复数初始化为0 + 0i- real = 0; img = 0; } complex(int r, int i){ //参数化的构造函数以初始化复数。 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