一个复数是一个形式为a+bi的数,这里的a和b都是实数,i是√-1的平方根。数字a和b分别称为复数的实部和虚部。可以使用下面的公式完成复数的加、减、乘、除:
加:a + bi + c + di = (a + c) + (b + d)i
减:a + bi - (c + di) = (a - c) + (b - d)i
乘:(a + bi) * (c + di) = (ac -bd) + (bc + ad)i
除:(a + bi) / (c + di) = (ac + bd)/(c*c + d*d) + (bc - ad)i/(c*c + d*d)
还可以使用下面的公式得到复数的绝对值:
|a + bi| = √(a *a + b*b)
要求:
编写一个测试程序,提示用户输入两个复数,然后显示它们做加、减、乘、除之后的结果。
package pack2;
public class Complex implements Cloneable{
private double a,b;
public Complex() {
this(0);
}
public Complex(double a) {
this.a = a;
}
public Complex(double a, double b) {
this.a = a;
this.b = b;
}
//返回复数的加法运算
public Complex add(Complex c) {
if(c == null) //如果c是null,抛出异常
throw new NullPointerException("Invalid Pointer");
return new Complex((a + c.a), (b + c.b));
}
//返回复数的减法运算
public Complex substract(Complex c) {
if(c == null)
throw new NullPointerException("Invalid Pointer");
return new Complex((a - c.a), (b - c.b));
}
//返回复数的乘法运算
public Complex multiply(Complex c) {
if(c == null)
throw new NullPointerException("Invalid Pointer");
return new Complex((a * c.a - b * c.b),(a * c.b + b * c.a));
}
//返回复数的除法运算
public Complex divide(Complex c) {
if(c == null)
throw new NullPointerException("Invalid Pointer");
return new Complex((a * c.a + b * c.b) / (Math.pow(c.a, 2) + Math.pow(c.b, 2)),
(b * c.a - a * c.b) / (Math.pow(c.a, 2) + Math.pow(c.b, 2)));
}
//返回复数的绝对值
public double abs() {
return Math.sqrt(a * a + b *b);
}
@Override
public String toString() {
if(Math.abs(b) < 0.00001)
//如果b为0,返回a(考虑到浮点数的精度变化,故用Math.abs()方法)
return ""+a;
else
return a+" + "+b+"i";
}
@Override //重写clone()方法
public Object clone(){
try {
return super.clone(); //调用本地方法返回克隆
}catch (CloneNotSupportedException e) {
return null;
}
}
//返回实部
public double getRealPart() {
return a;
}
//返回虚部
public double getImginaryPart() {
return b;
}
//设置实部
public void setRealPart(double a) {
this.a = a;
}
//设置虚部
public void setImginaryPart(double b) {
this.b = b;
}
}
测试程序如下:
package pack2;
import java.util.Scanner;
public class TestComplex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first complex number: ");
double a = input.nextDouble();
double b = input.nextDouble();
System.out.print("Enter the second complex number: ");
double c = input.nextDouble();
double d = input.nextDouble();
Complex complex = new Complex(a,b);
Complex complex1 = new Complex(c,d);
System.out.printf("(%.1f + %.1fi) + (%.1f + %.1fi) =
%s\n",a,b,c,d,complex.add(complex1));
System.out.printf("(%.1f + %.1fi) - (%.1f + %.1fi) =
%s\n",a,b,c,d,complex.substract(complex1));
System.out.printf("(%.1f + %.1fi) * (%.1f + %.1fi) = %s\n",a,b,c,d,complex.multiply(complex1));
System.out.printf("(%.1f + %.1fi) / (%.1f + %.1fi) = %s\n",a,b,c,d,complex.divide(complex1));
System.out.printf("|(%.1f + %.1fi)| = %.15f\n",a,b,complex.getSoluteValue());
input.close();
}
}