定义一个复数类,并实现以下复数类的方法:构造方法、得到实、虚部、设置实部、虚部、复数的加法,减法,乘法,最后,创建对象进行运算。用java编写
时间: 2024-10-23 14:06:13 浏览: 23
一个复数类的计算
为了定义一个复数类并实现所需的方法,我们可以使用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 void setReal(double real) {
this.real = real;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
// 复数加法
public ComplexNumber add(ComplexNumber other) {
double realPart = this.real + other.getReal();
double imaginaryPart = this.imaginary + other.getImaginary();
return new ComplexNumber(realPart, imaginaryPart);
}
// 复数减法
public ComplexNumber subtract(ComplexNumber other) {
double realPart = this.real - other.getReal();
double imaginaryPart = this.imaginary - other.getImaginary();
return new ComplexNumber(realPart, imaginaryPart);
}
// 复数乘法
public ComplexNumber multiply(ComplexNumber other) {
double realPart = this.real * other.getReal() - this.imaginary * other.getImaginary();
double imaginaryPart = this.real * other.getImaginary() + this.imaginary * other.getReal();
return new ComplexNumber(realPart, imaginaryPart);
}
// 打印复数
@Override
public String toString() {
if (imaginary >= 0) {
return "(" + real + " + " + imaginary + "i)";
} else {
return "(" + real + " - " + (-imaginary) + "i)";
}
}
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(2, 3);
ComplexNumber c2 = new ComplexNumber(-1, 4);
System.out.println("c1: " + c1); // 输出 (2 + 3i)
System.out.println("c2: " + c2); // 输出 (-1 + 4i)
ComplexNumber sum = c1.add(c2);
System.out.println("Sum: " + sum); // 输出 (1 + 7i)
ComplexNumber diff = c1.subtract(c2);
System.out.println("Difference: " + diff); // 输出 (3 - 1i)
ComplexNumber product = c1.multiply(c2);
System.out.println("Product: " + product); // 输出 (10 - 5i)
}
}
```
这个例子中,我们定义了一个`ComplexNumber`类,包含了构造方法、getter和setter方法,以及复数之间的加法、减法和乘法操作。在`main`方法中,我们创建了两个复数对象,并进行了相应的运算。
阅读全文