21xrx.com
2025-04-22 23:04:47 Tuesday
文章检索 我的文章 写文章
Java中复数的表示方法
2023-06-15 20:43:14 深夜i     10     0
Java 复数 实现

在Java中,我们常常会遇到需要表示复数的情况(例如在数学或者工程计算中)。那么Java中应该如何表示复数呢?

Java并没有直接提供复数类型,但是我们可以使用自定义类来表示复数。下面是一个简单的复数类的实现,它包含了两个私有变量:实部和虚部,以及一些用于操作复数的方法。

public class Complex {
  private double real;
  private double imag;
  public Complex(double real, double imag)
    this.real = real;
    this.imag = imag;
  
  public double getReal()
    return real;
  
  public double getImag()
    return imag;
  
  public Complex add(Complex other) {
    return new Complex(real + other.real, imag + other.imag);
  }
  public Complex sub(Complex other) {
    return new Complex(real - other.real, imag - other.imag);
  }
  public Complex mult(Complex other) {
    return new Complex(real * other.real - imag * other.imag,
              real * other.imag + imag * other.real);
  }
  // ... 其他方法
}

使用这个类表示复数的示例如下:

Complex a = new Complex(1, 2); // 1+2i
Complex b = new Complex(3, -4); // 3-4i
Complex c = a.add(b); // 4-2i
Complex d = a.mult(b); // 11-2i

通过实现一个复数类,我们可以方便地表示和操作复数了。但需要注意的是,这只是一个简单的实现示例,还有许多细节需要考虑,例如复数的精度问题、异常处理等等。

  
  

评论区

请求出错了