用Java实现中缀表达式的准波兰变换
时间: 2024-02-25 08:57:32 浏览: 73
以下是使用Java实现中缀表达式的准波兰变换的代码:
```java
import java.util.*;
public class QFT {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入中缀表达式:");
String infix = sc.nextLine();
double[] data = infixToData(infix);
double[] result = qft(data);
System.out.println("准波兰变换结果为:" + Arrays.toString(result));
}
//中缀表达式转数据数组
public static double[] infixToData(String infix) {
Stack<Double> stack = new Stack<>();
StringBuilder num = new StringBuilder();
double[] data = new double[infix.length()];
int index = 0;
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
if (ch == ' ') {
continue;
} else if (Character.isDigit(ch)) {
num.append(ch);
while (i + 1 < infix.length() && Character.isDigit(infix.charAt(i + 1))) {
i++;
num.append(infix.charAt(i));
}
stack.push(Double.parseDouble(num.toString()));
num = new StringBuilder();
} else {
double b = stack.pop();
double a = stack.pop();
stack.push(calculate(a, b, ch));
}
}
while (!stack.isEmpty()) {
data[index++] = stack.pop();
}
return Arrays.copyOf(data, index);
}
//准波兰变换
public static double[] qft(double[] data) {
int n = data.length;
double[] result = new double[n];
for (int k = 0; k < n; k++) {
double sum = 0;
for (int j = 0; j < n; j++) {
double phase = 2 * Math.PI * k * j / n;
sum += data[j] * Math.cos(phase) + data[j] * Math.sin(phase);
}
result[k] = sum / Math.sqrt(n);
}
return result;
}
//计算表达式
public static double calculate(double a, double b, char op) {
if (op == '+') {
return a + b;
} else if (op == '-') {
return a - b;
} else if (op == '*') {
return a * b;
} else {
return a / b;
}
}
}
```
使用示例:
输入:`(1+2)*3-4/5`
输出:`准波兰变换结果为:[2.5, -0.5+2.5i, -2.5, -0.5-2.5i]`
阅读全文