Java实现复数相乘
时间: 2024-11-03 20:21:44 浏览: 10
在Java中,我们可以创建一个名为`ComplexNumber`的类来表示复数,并提供相应的加法、减法、乘法等操作,包括复数之间的相乘。以下是一个简单的例子:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 复数相乘的运算
public ComplexNumber multiply(ComplexNumber other) {
double newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(newReal, newImaginary);
}
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
// getter and setter methods for real and imaginary parts
}
// 示例
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(2, 3);
ComplexNumber c2 = new ComplexNumber(4, -5);
ComplexNumber result = c1.multiply(c2);
System.out.println("Multiplication of (" + c1 + ") and (" + c2 + ") is: " + result);
}
```
在这个示例中,`multiply`方法接收另一个`ComplexNumber`作为参数,通过标准的复数乘法规则计算出新的实部和虚部。然后创建一个新的`ComplexNumber`实例返回结果。
阅读全文