JAVA_实现两个复数的四则运算

时间:2024-04-17 18:55:55

1、一个复数类Complex由两部分组成:实部real和虚部imaginary,两个复数可以进行加减乘除四则运算。
  试设计这个复数类,然后在另一个类的程序入口演示。

 

public class Test {
public static void main(String[] args) {
// 定义两个对象并赋值:c1(a+bi)=(2+4i),c2=(c+di)=(6+16i)
Complex c1=new Complex();
c1.real=2;
c1.imaginary=4;
Complex c2=new Complex();
c2.real=6;
c2.imaginary=16;

// 以字符串的方式输出:采用标准格式输出,即a+bi
System.out.println("两个复数相加得:"+c1.add(c2));

// 在每次调用并运算(此时real值发生变化)之后,再重新赋值:
c1.real=2;
c1.imaginary=4;

System.out.println("两个复数相减得:"+c1.sub(c2));
c1.real=2;
c1.imaginary=4;

System.out.println("两个复数相乘得:"+c1.mul(c2));
c1.real=2;
c1.imaginary=4;

System.out.println("两个复数相除得:"+c1.div(c2));
}
}
class Complex
{
double real;
double imaginary;
//最后以字符串输出的格式:
//1.虚部为正值时,实部+"+"+虚部+"i" 2.虚部为0时,只有实部,即实部+"" 3.虚部为负值时,实部+""+虚部+"i"

// 加法,减法:直接实部加减实部,虚部加减虚部
String add(Complex c)
{
if(imaginary+c.imaginary>0)
return (real=real+c.real)+"+"+(imaginary=imaginary+c.imaginary)+"i";
else if(imaginary+c.imaginary==0)
return (real=real+c.real)+"";
else
return (real=real+c.real)+""+(imaginary=imaginary+c.imaginary)+"i";
}
String sub(Complex c)
{
if(imaginary-c.imaginary>0)
return (real=real-c.real)+"+"+(imaginary=imaginary-c.imaginary)+"i";
else if(imaginary-c.imaginary==0)
return (real=real-c.real)+"";
else
return (real=real-c.real)+""+(imaginary=imaginary-c.imaginary)+"i";
}
// 乘法的公式:(a+bi)*(c+di) = a*c + bi*c + a*di + bi*di = a*c + (b*d)(i^2) + (b*c+a*d)i

// 注:此处的i^2直接赋值-1,即 return a*c-b*d+(b*c+a*d)i
String mul(Complex c)
{
if(imaginary*c.real+real*c.imaginary>0)
return (real*c.real)-(imaginary*c.imaginary)+"+"+(imaginary*c.real+real*c.imaginary)+"i";
else if(imaginary*c.real+real*c.imaginary==0)
return (real*c.real)-(imaginary*c.imaginary)+"";
else
return (real*c.real)-(imaginary*c.imaginary)+""+(imaginary*c.real+real*c.imaginary)+"i";
}
// 除法的公式:(a+bi)/(c+di) = (a+bi)*(c-di) / c^2+d^2

// 注:在乘法的基础上得到格式A+Bdi,再进行A /c^2+d^2,B /c^2+d^2 + "i"
String div(Complex c)
{
if(imaginary*c.real-real*c.imaginary>0)
return ((real*c.real)+(imaginary*c.imaginary))/(c.real*c.real+c.imaginary*c.imaginary)+"+"+(imaginary*c.real-real*c.imaginary)/(c.real*c.real+c.imaginary*c.imaginary)+"i";
else if(imaginary*c.real-real*c.imaginary==0)
return ((real*c.real)+(imaginary*c.imaginary))/(c.real*c.real+c.imaginary*c.imaginary)+"";
else
return ((real*c.real)+(imaginary*c.imaginary))/(c.real*c.real+c.imaginary*c.imaginary)+""+(imaginary*c.real-real*c.imaginary)/(c.real*c.real+c.imaginary*c.imaginary)+"i";

}
}
/*Complex c1=new Complex();
c1.real=2;
c1.imaginary=4;

Complex c2=new Complex();
c2.real=6;
c2.imaginary=16;
即:c1=2+4i
c2=6+16i
数学运算结果:

两者相加:8+20i
两者相减:-4-12i

两者相乘:-52+56i
(2+4i)*(6+16i)

两者相除:0.2602739726027397-0.0273972602739726i
(2+4i)/(6+16i)=(2+4i)*(6-16i)/(6*6+16*16)*/