使用BufferedReader实现Java虚数的四则运算
时间: 2023-12-12 17:28:32 浏览: 108
本题需要实现Java虚数的四则运算,其中虚数的格式为"a+bi",其中a和b为实数,i为虚数单位。四则运算包括加、减、乘、除四种运算。
我们可以使用BufferedReader读取用户输入的虚数表达式,然后解析表达式中的实数和虚数单位,进行四则运算后输出结果。具体实现如下:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ComplexNumber {
private double real;
private double imag;
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imag + other.imag);
}
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imag - other.imag);
}
public ComplexNumber multiply(ComplexNumber other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new ComplexNumber(real, imag);
}
public ComplexNumber divide(ComplexNumber other) {
double denominator = other.real * other.real + other.imag * other.imag;
double real = (this.real * other.real + this.imag * other.imag) / denominator;
double imag = (this.imag * other.real - this.real * other.imag) / denominator;
return new ComplexNumber(real, imag);
}
public String toString() {
return this.real + "+" + this.imag + "i";
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入第一个虚数,格式为a+bi:");
String input1 = reader.readLine();
System.out.println("请输入第二个虚数,格式为a+bi:");
String input2 = reader.readLine();
ComplexNumber c1 = parseComplexNumber(input1);
ComplexNumber c2 = parseComplexNumber(input2);
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
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));
}
private static ComplexNumber parseComplexNumber(String input) {
int plusIndex = input.indexOf("+");
int iIndex = input.indexOf("i");
double real = Double.parseDouble(input.substring(0, plusIndex));
double imag = Double.parseDouble(input.substring(plusIndex + 1, iIndex));
return new ComplexNumber(real, imag);
}
}
```
在上面的代码中,我们定义了一个ComplexNumber类来表示虚数,其中包含了四种四则运算的实现。在main函数中,我们使用BufferedReader读取用户输入的两个虚数,然后使用parseComplexNumber函数解析出虚数的实数和虚数单位,然后进行四则运算并输出结果。parseComplexNumber函数使用了String的substring函数来截取实数和虚数单位,并使用Double.parseDouble将字符串转换为实数。
阅读全文