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 void setReal(double real) {
    this.real = real;
}

public double getImaginary() {
    return imaginary;
}

public void setImaginary(double imaginary) {
    this.imaginary = imaginary;
}

public ComplexNumber add(ComplexNumber other) {
    return new ComplexNumber(real + other.real, imaginary + other.imaginary);
}

public ComplexNumber subtract(ComplexNumber other) {
    return new ComplexNumber(real - other.real, imaginary - other.imaginary);
}

public ComplexNumber multiply(ComplexNumber other) {
    double newReal = real * other.real - imaginary * other.imaginary;
    double newImaginary = real * other.imaginary + 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 = (real * other.real + imaginary * other.imaginary) / denominator;
    double newImaginary = (imaginary * other.real - real * other.imaginary) / denominator;
    return new ComplexNumber(newReal, newImaginary);
}

@Override
public String toString() {
    if (imaginary == 0) {
        return String.format("%.2f", real);
    } else if (real == 0) {
        return String.format("%.2fi", imaginary);
    } else {
        return String.format("%.2f%+.2fi", real, imaginary);
    }
}
用java编写一个复数类即该类有两个变量实部real和虚部imaginary都是double类型

原文地址: https://www.cveoy.top/t/topic/hsNr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录