用Java编写一个复数加减乘除的代码并举例运行
时间: 2024-10-28 11:10:42 浏览: 4
Java中复数类的计算,对复数进行加减乘除
在Java中,我们可以创建一个名为`ComplexNumber`的类来表示复数,并提供加、减、乘、除的方法。首先,我们需要包含两个double类型的成员变量来存储实部和虚部。这里是一个简单的实现:
```java
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// Getters and Setters for real and imaginary parts
// 加法
public ComplexNumber add(ComplexNumber other) {
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.real - other.real;
double newImaginary = this.imaginary - other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
// 乘法
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);
}
// 除法,假设其他数不为0
public ComplexNumber divide(ComplexNumber other) {
double denominator = Math.pow(other.real, 2) + Math.pow(other.imaginary, 2);
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new ComplexNumber(newReal, newImaginary);
}
}
// 示例
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(2, 3);
ComplexNumber c2 = new ComplexNumber(-1, 4);
System.out.println("c1: (" + c1.real + ", " + c1.imaginary + ")");
System.out.println("c2: (" + c2.real + ", " + c2.imaginary + ")");
ComplexNumber sum = c1.add(c2);
System.out.println("Addition: " + sum.toString());
ComplexNumber diff = c1.subtract(c2);
System.out.println("Subtraction: " + diff.toString());
ComplexNumber product = c1.multiply(c2);
System.out.println("Multiplication: " + product.toString());
if (!c2.isZero()) { // 检查除数是否为零
ComplexNumber quotient = c1.divide(c2);
System.out.println("Division: " + quotient.toString());
} else {
System.out.println("Cannot divide by zero.");
}
}
```
在这个例子中,我们创建了两个复数`c1`和`c2`,然后演示了如何通过`add`, `subtract`, `multiply`, 和`divide`方法来进行操作。注意,对于除法,我们在计算之前检查了除数是否为零,以避免异常。
阅读全文