java复数类加减乘除运算
- 格式:docx
- 大小:36.78 KB
- 文档页数:4
java复数类加减乘除运算
以下是一个简单的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 other) {
double real = this.real + other.real;
double imaginary = this.imaginary + other.imaginary;
return new ComplexNumber(real, imaginary);
}
// 减去另一个复数
public ComplexNumber subtract(ComplexNumber other) {
double real = this.real - other.real;
double imaginary = this.imaginary - other.imaginary;
return new ComplexNumber(real, imaginary);
}
// 乘以另一个复数
public ComplexNumber multiply(ComplexNumber other) {
double real = this.real * other.real - this.imaginary
* other.imaginary;
double imaginary = this.real * other.imaginary +
this.imaginary * other.real;
return new ComplexNumber(real, imaginary); }
// 除以另一个复数
public ComplexNumber divide(ComplexNumber other) {
double divisor = other.real * other.real +
other.imaginary * other.imaginary;
if (divisor == 0) {
throw new IllegalArgumentException("Divisor
cannot be zero.");
}
double real = (this.real * other.real +
this.imaginary * other.imaginary) / divisor;
double imaginary = (this.imaginary * other.real -
this.real * other.imaginary) / divisor;
return new ComplexNumber(real, imaginary);
}
}
```
你可以这样使用它:
```java
public class Main {
public static void main(String[] args) { ComplexNumber a = new ComplexNumber(1, 2); // 1+2i
ComplexNumber b = new ComplexNumber(3, 4); // 3+4i
ComplexNumber sum = a.add(b); // (1+3)+(2+4)i = 4+6i
ComplexNumber difference = a.subtract(b); // (1-3)+(2-4)i = -2+2i
ComplexNumber product = a.multiply(b); //
(1*3)+(2*4)i = 3+8i
ComplexNumber quotient = a.divide(b); //
((1*3+2*4)/(3*3+4*4))+((2*3-1*4)/(3*3+4*4))i = 0.6+0.4i
System.out.println("Sum: " + sum); // Sum: 4.0+6.0i
System.out.println("Difference: " + difference); //
Difference: -2.0+2.0i
System.out.println("Product: " + product); // Product:
3.0+8.0i
System.out.println("Quotient: " + quotient); //
Quotient: 0.6+0.4i
}
}
```