用java构造实部与虚部_声明Complex类,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数、复数加法、减法,字符串描述、比较相等等操作...
时间: 2024-02-03 22:03:34 浏览: 98
java .定义一个复数类 complex ,它的内部具有两个实例变量:realPart和imagPart,分别代表复数的实部和虚
4星 · 用户满意度95%
下面是一个简单的Java代码示例,用于构造实部和虚部,声明Complex类和实现一些常见的操作:
```java
public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 由字符串构造复数
public static Complex fromString(String str) {
String[] parts = str.split("\\+");
double real = Double.parseDouble(parts[0]);
double imaginary = Double.parseDouble(parts[1].replace("i", ""));
return new Complex(real, imaginary);
}
// 复数加法
public Complex add(Complex other) {
return new Complex(real + other.real, imaginary + other.imaginary);
}
// 复数减法
public Complex subtract(Complex other) {
return new Complex(real - other.real, imaginary - other.imaginary);
}
// 字符串描述
public String toString() {
return real + "+" + imaginary + "i";
}
// 比较相等
public boolean equals(Complex other) {
return real == other.real && imaginary == other.imaginary;
}
}
```
使用示例:
```java
Complex c1 = new Complex(3, 4);
Complex c2 = Complex.fromString("2+5i");
Complex c3 = c1.add(c2);
Complex c4 = c1.subtract(c2);
System.out.println(c1.toString()); // 输出 "3.0+4.0i"
System.out.println(c2.toString()); // 输出 "2.0+5.0i"
System.out.println(c3.toString()); // 输出 "5.0+9.0i"
System.out.println(c4.toString()); // 输出 "1.0-1.0i"
System.out.println(c1.equals(c2)); // 输出 "false"
```
阅读全文