java复数四则运算
时间: 2023-11-12 11:56:22 浏览: 90
对于复数的四则运算,已按题目要求正确编写程序,并运行得到正确结果
Java中可以通过使用复数的实部和虚部来进行四则运算。以下是一个示例代码,展示了如何在Java中实现复数的加法、减法、乘法和除法运算:
```java
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) {
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber subtract(ComplexNumber other) {
double newReal = this.real - other.real;
double newImaginary = this.imaginary - other.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
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 divisor = Math.pow(other.real, 2) + Math.pow(other.imaginary, 2);
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / divisor;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / divisor;
return new ComplexNumber(newReal, newImaginary);
}
@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}
public class Main {
public static void main(String[] args) {
ComplexNumber a = new ComplexNumber(2, 3);
ComplexNumber b = new ComplexNumber(4, 5);
ComplexNumber sum = a.add(b);
System.out.println("Sum: " + sum);
ComplexNumber difference = a.subtract(b);
System.out.println("Difference: " + difference);
ComplexNumber product = a.multiply(b);
System.out.println("Product: " + product);
ComplexNumber quotient = a.divide(b);
System.out.println("Quotient: " + quotient);
}
}
```
阅读全文