引言
在Java编程语言中,复数是一种常见的数学对象,由实部和虚部组成。虽然Java标准库中没有内置复数类,但我们可以自己编写一个。本文将带你从零开始,创建一个简单的复数类,并实现基本的数学运算:加法、减法、乘法和除法。
准备工作
在开始之前,请确保你的计算机上已经安装了Java开发环境,包括JDK和IDE(如IntelliJ IDEA或Eclipse)。
创建复数类
首先,我们需要创建一个名为ComplexNumber的类。这个类将包含两个私有成员变量来存储实部和虚部。
public class ComplexNumber {
private double real;
private double imaginary;
// 构造函数
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 加法
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imaginary + other.imaginary);
}
// 减法
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imaginary - other.imaginary);
}
// 乘法
public ComplexNumber multiply(ComplexNumber other) {
double newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(newReal, newImaginary);
}
// 除法
public ComplexNumber divide(ComplexNumber other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new ComplexNumber(newReal, newImaginary);
}
// 重写toString方法,方便输出复数
@Override
public String toString() {
return "(" + real + " + " + imaginary + "i)";
}
}
测试复数类
现在我们已经创建了复数类,接下来我们可以通过一些测试用例来验证它的功能。
public class Main {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(3, 2);
ComplexNumber c2 = new ComplexNumber(1, 7);
System.out.println("c1 + c2 = " + c1.add(c2));
System.out.println("c1 - c2 = " + c1.subtract(c2));
System.out.println("c1 * c2 = " + c1.multiply(c2));
System.out.println("c1 / c2 = " + c1.divide(c2));
}
}
结论
通过本文,我们成功地创建了一个简单的复数类,并实现了基本的数学运算。这是一个很好的实践,可以帮助你更好地理解面向对象编程和Java语言。你可以进一步扩展这个类,添加更多的功能,如复数的模、共轭复数等。
