Java编写一个复数类,具有实部虚部成员变量,可以完成加减 乘除获得实部虚部等操作,并编写一个主类对其进行测试
时间: 2024-10-24 22:10:04 浏览: 19
C#实现复数类,包括加减乘除乘方开方N次方等操作
在Java中,我们可以创建一个名为`ComplexNumber`的类来表示复数,包括实部(realPart)和虚部(imaginaryPart)作为成员变量。这里是一个简单的示例:
```java
public class ComplexNumber {
private double realPart;
private double imaginaryPart;
// 构造函数
public ComplexNumber(double real, double imaginary) {
this.realPart = real;
this.imaginaryPart = imaginary;
}
// 获取实部和虚部
public double getRealPart() {
return realPart;
}
public double getImaginaryPart() {
return imaginaryPart;
}
// 加法运算
public ComplexNumber add(ComplexNumber other) {
double newReal = this.realPart + other.getRealPart();
double newImaginary = this.imaginaryPart + other.getImaginaryPart();
return new ComplexNumber(newReal, newImaginary);
}
// 减法运算
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.realPart - other.getRealPart();
double newImaginary = this.imaginaryPart - other.getImaginaryPart();
return new ComplexNumber(newReal, newImaginary);
}
// 乘法运算
public ComplexNumber multiply(ComplexNumber other) {
double realProduct = this.realPart * other.getRealPart() - this.imaginaryPart * other.getImaginaryPart();
double imaginaryProduct = this.realPart * other.getImaginaryPart() + this.imaginaryPart * other.getRealPart();
return new ComplexNumber(realProduct, imaginaryProduct);
}
// 除法运算(假设除数不为0)
public ComplexNumber divide(ComplexNumber divisor) {
double denominator = divisor.getRealPart() * divisor.getRealPart() + divisor.getImaginaryPart() * divisor.getImaginaryPart();
double newReal = (this.realPart * divisor.getRealPart() + this.imaginaryPart * divisor.getImaginaryPart()) / denominator;
double newImaginary = (this.imaginaryPart * divisor.getRealPart() - this.realPart * divisor.getImaginaryPart()) / denominator;
return new ComplexNumber(newReal, newImaginary);
}
// 打印复数
@Override
public String toString() {
return "Complex Number (" + realPart + " + " + imaginaryPart + "i)";
}
}
```
接下来,在`Main`类中我们可以对这个复数类进行测试:
```java
public class Main {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(3, 4);
ComplexNumber c2 = new ComplexNumber(1, 2);
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
ComplexNumber sum = c1.add(c2);
System.out.println("Sum: " + sum);
ComplexNumber difference = c1.subtract(c2);
System.out.println("Difference: " + difference);
ComplexNumber product = c1.multiply(c2);
System.out.println("Product: " + product);
try {
ComplexNumber quotient = c1.divide(c2);
System.out.println("Quotient: " + quotient);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
```
在这个例子中,我们创建了两个复数对象,进行了加、减、乘、除的操作,并打印出结果。
阅读全文