java7-4 复数类的定义
时间: 2024-09-29 21:11:26 浏览: 35
java复数四则运算-类的定义与对象.rar
5星 · 资源好评率100%
在Java 7中,复数类的定义通常是通过`Complex`或`Pair`这样的命名来实现的,因为Java本身并不内置复数类型的原生支持。一个简单的复数类可能会像这样定义:
```java
import java.util.Arrays;
public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造方法,实部和虚部可以单独传递
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 构造方法,从数组接收实部和虚部
public Complex(double[] parts) {
this(real: parts[0], imaginary: parts[1]);
}
// 获取复数属性
public double getReal() { return real; }
public double getImaginary() { return imaginary; }
// 设定复数属性
public void setReal(double real) { this.real = real; }
public void setImaginary(double imaginary) { this.imaginary = imaginary; }
// 重载加法、减法、乘法和除法等操作符
public Complex add(Complex other) { ... }
public Complex subtract(Complex other) { ... }
public Complex multiply(Complex other) { ... }
public Complex divide(Complex other) throws ArithmeticException { ... }
// 显示复数为 "a + bi"
@Override
public String toString() {
return String.format("%.2f + %.2fi", real, imaginary);
}
}
阅读全文