建立一个复数类 Complex,要求 1. 含两个私有数据成员:real, imaginary,float类型 2.公有成员函数包括如下功能: 设置复数的两个私有成员 输出这个复数 与另一复数的加法函数 原型为 add (Complex c); 判断与另一复数是否相等isEqual(Complex c); 在main函数中,输入两个复数,判断两个复数是否相等(实部和虚部要分别相等),然后两者相加之和赋值给一个新的复数,并输出
时间: 2023-04-10 19:01:05 浏览: 103
好的,这是一个关于编程的问题,我可以回答。以下是Complex类的代码实现:
```c++
class Complex {
private:
float real;
float imaginary;
public:
void setComplex(float r, float i) {
real = r;
imaginary = i;
}
void outputComplex() {
cout << real << " + " << imaginary << "i" << endl;
}
Complex add(Complex c) {
Complex result;
result.real = real + c.real;
result.imaginary = imaginary + c.imaginary;
return result;
}
bool isEqual(Complex c) {
return (real == c.real && imaginary == c.imaginary);
}
};
int main() {
Complex c1, c2, c3;
float r, i;
cout << "Enter the real and imaginary parts of the first complex number: ";
cin >> r >> i;
c1.setComplex(r, i);
cout << "Enter the real and imaginary parts of the second complex number: ";
cin >> r >> i;
c2.setComplex(r, i);
if (c1.isEqual(c2)) {
cout << "The two complex numbers are equal." << endl;
} else {
cout << "The two complex numbers are not equal." << endl;
}
c3 = c1.add(c2);
cout << "The sum of the two complex numbers is: ";
c3.outputComplex();
return 0;
}
```
以上代码实现了一个Complex类,包括了设置复数的两个私有成员、输出这个复数、与另一复数的加法函数和判断与另一复数是否相等的函数。在main函数中,输入两个复数,判断两个复数是否相等,然后两者相加之和赋值给一个新的复数,并输出。