复数java实验_java实验 复数
时间: 2023-08-31 13:12:42 浏览: 90
java实验一 图形 字符串 复数
4星 · 用户满意度95%
好的,以下是一个基本的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 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);
}
public String toString() {
if (imaginary < 0) {
return real + " - " + (-imaginary) + "i";
} else {
return real + " + " + imaginary + "i";
}
}
}
```
这个类定义了一个名为ComplexNumber的复数类,包含实部和虚部。您可以通过调用实例方法来执行以下操作:
- add():添加两个复数。
- subtract():从两个复数中减去一个。
- multiply():将两个复数相乘。
- divide():将两个复数相除。
- toString():将复数作为字符串返回。
以下是一个简单的示例,演示如何使用ComplexNumber类:
```java
public class Main {
public static void main(String[] args) {
ComplexNumber c1 = new ComplexNumber(1, 2);
ComplexNumber c2 = new ComplexNumber(3, 4);
ComplexNumber sum = c1.add(c2);
ComplexNumber difference = c1.subtract(c2);
ComplexNumber product = c1.multiply(c2);
ComplexNumber quotient = c1.divide(c2);
System.out.println("c1: " + c1.toString());
System.out.println("c2: " + c2.toString());
System.out.println("Sum: " + sum.toString());
System.out.println("Difference: " + difference.toString());
System.out.println("Product: " + product.toString());
System.out.println("Quotient: " + quotient.toString());
}
}
```
输出结果:
```
c1: 1.0 + 2.0i
c2: 3.0 + 4.0i
Sum: 4.0 + 6.0i
Difference: -2.0 - 2.0i
Product: -5.0 + 10.0i
Quotient: 0.44 + 0.08i
```
希望这个例子能够对你有所帮助!
阅读全文