复数类的基本运算

package lei;

public class complex {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Complex a=new Complex(3,4);
	Complex b=new Complex(2,1);
	Complex c=a.Add(b);
	Complex d=a.dec(b);

	Complex e=a.mul(b);
	Complex f=a.div(b);
	System.out.println("复数a="+a.tosting());
	System.out.println("复数b="+b.tosting());
	System.out.println("复数相加为"+c.tosting());
	
	System.out.println("复数相减"+d.tosting());
    System.out.println("复数a共轭为"+a.con());
    System.out.println("复数b共轭为"+b.con());
	System.out.println("复数相乘"+e.tosting());
	System.out.println("复数相除"+f.tosting());
}

}

class Complex
{
 double real;
 double img;
Complex()             //初始化
{
	real=0;
	img=0;
}
Complex(double n1,double n2)    //具体传参数
{
	real=n1;
	img=n2;
}
String tosting()
{
	return real+"+"+img+"i";    //复数显示
}
Complex Add(Complex b)     //复数的加法
{
	Complex c=new Complex();
	c.real=this.real+b.real;
	c.img=this.img+b.img;
	return c;
}
Complex dec(Complex b)     //复数的减法
{
	Complex c=new Complex();
	c.real=this.real-b.real;
	c.img=this.img-b.img;
	return c;
}
String con()     //共轭
{
	return real+"-"+img+"i";
}
Complex mul(Complex b)     //复数的乘法
{
	Complex d=new Complex();
	d.real=this.real*b.real-this.img*b.img;
	d.img=this.real*b.img+this.img*b.real;
	return d;
}
Complex div (Complex b)     //复数的乘法
{
	Complex d=new Complex();
	d.real=(this.real*b.real+this.img*b.img)/(b.real*b.real+b.img*b.img);
	d.img=(-this.real*b.img+this.img*b.real)/(b.real*b.real+b.img*b.img);
	return d;
}
}
发布了16 篇原创文章 · 获赞 11 · 访问量 649

猜你喜欢

转载自blog.csdn.net/qq_44981039/article/details/102885504