//20、定义一个复数类

//20、定义一个复数类,并为其重载>>和<<运算符,使得复数对象可以整体输入输出,并给出main()对该类进行应用。
#include"iostream"
using namespace std;
class complex1
{
private:
    int real,iamg;
public:
    //complex1(int x=0,int y=0):real(x),iamg(y){}

    friend ostream &operator<<(ostream &out,complex1 &c);
     friend istream &operator>>(istream &in,complex1 &c);

};
int main()
{

    complex1  c1;
    cin>>c1;
    cout<<c1;
    return 0;

}
istream &operator>>(istream &in,complex1 &c)
{
   in>>c.real;
   in>>c.iamg;
   return in;
}
ostream &operator<<(ostream &out,complex1 &c)
{
    out<<c.real;
    if(c.iamg>0)
        out<<"+";
    out<<c.iamg<<"i"<<endl;
    return out;
}
 

在编程中,定义一个复数类`complex`通常是为了处理复数的数学运算。复数是由实部虚部组成的数,通常表示为 a + bi 的形式,其中 a 是实部,b 是虚部,i 是虚数单位,满足 i² = -1。一个简单的复数类定义可能包含以下内容: ```java public class Complex { // 实部虚部属性 private double real; private double imaginary; // 构造方法 public Complex(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } // 实部获取方法 public double getReal() { return real; } // 虚部获取方法 public double getImaginary() { return imaginary; } // 复数加法 public Complex add(Complex other) { return new Complex(this.real + other.real, this.imaginary + other.imaginary); } // 复数减法 public Complex subtract(Complex other) { return new Complex(this.real - other.real, this.imaginary - other.imaginary); } // 复数乘法 public Complex multiply(Complex other) { double newReal = this.real * other.real - this.imaginary * other.imaginary; double newImaginary = this.real * other.imaginary + this.imaginary * other.real; return new Complex(newReal, newImaginary); } // 复数除法 public Complex divide(Complex other) { double denominator = other.real * other.real + other.imaginary * other.imaginary; double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator; double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator; return new Complex(newReal, newImaginary); } // 复数的字串表示 @Override public String toString() { return "(" + real + " + " + imaginary + "i)"; } } ``` 这个类定义了一个复数的结构和基本操作,包括加、减、乘、除运算以及复数的字串表示方法。使用这个类可以创建复数对象,并执行基本的复数运算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值