用Java编写一个程序,实现复数运算,要求如下: 1) 设计并实现复数类。 2) 设计并实现复数的加、减、乘、除运算。以提供任意数值类型数据与复数对象实例自身的运算功能。
时间: 2024-03-20 11:45:32 浏览: 111
好的,以下是Java代码实现:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public ComplexNumber add(ComplexNumber c) {
return new ComplexNumber(real + c.real, imaginary + c.imaginary);
}
public ComplexNumber subtract(ComplexNumber c) {
return new ComplexNumber(real - c.real, imaginary - c.imaginary);
}
public ComplexNumber multiply(ComplexNumber c) {
double realPart = real * c.real - imaginary * c.imaginary;
double imaginaryPart = real * c.imaginary + imaginary * c.real;
return new ComplexNumber(realPart, imaginaryPart);
}
public ComplexNumber divide(ComplexNumber c) {
double denominator = c.real * c.real + c.imaginary * c.imaginary;
double realPart = (real * c.real + imaginary * c.imaginary) / denominator;
double imaginaryPart = (imaginary * c.real - real * c.imaginary) / denominator;
return new ComplexNumber(realPart, imaginaryPart);
}
public String toString() {
String sign = (imaginary < 0) ? "-" : "+";
return String.format("%.2f %s %.2fi", real, sign, Math.abs(imaginary));
}
}
```
在这个复数类中,我们定义了两个属性 real 和 imaginary 分别表示实部和虚部,定义了构造方法、getter 方法和四个运算方法:加、减、乘、除。通过调用这些方法,我们可以对复数进行运算,并返回一个新的复数对象实例。
以下是一个简单的测试代码:
```java
public class Test {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1, 2);
ComplexNumber c2 = new ComplexNumber(3, -4);
ComplexNumber sum = c1.add(c2);
ComplexNumber difference = c1.subtract(c2);
ComplexNumber product = c1.multiply(c2);
ComplexNumber quotient = c1.divide(c2);
System.out.println(c1 + " + " + c2 + " = " + sum);
System.out.println(c1 + " - " + c2 + " = " + difference);
System.out.println(c1 + " * " + c2 + " = " + product);
System.out.println(c1 + " / " + c2 + " = " + quotient);
}
}
```
输出结果如下:
```
1.00 + 2.00i + 3.00 - 4.00i = 4.00 - 2.00i
1.00 + 2.00i - 3.00 + 4.00i = -2.00 + 6.00i
1.00 + 2.00i * 3.00 - 4.00i = 11.00 + 2.00i
1.00 + 2.00i / 3.00 - 4.00i = -0.20 + 0.40i
```
这个程序可以实现复数的加、减、乘、除运算,并支持任意数值类型数据与复数对象实例自身的运算功能。
阅读全文