计算器的制作Part1

最近一周的数据结构课将了一种数据结构-栈,老师说编写一个可以混合运算的计算器需要用的这个,于是在课下花了两天的时间写了一个可以实现混合运算的计算器。

这一部分主要介绍下后缀表达式及其的求值

表达式的表示形式有中缀、前缀和后缀3中形式。

中缀表达式按操作符的优先级进行计算,即我们一般常用的数学式子。

前缀表达式是将运算符放在两操作数的前面。这种表示法经常用于计算机科学,特别是编译器设计方面(这个不是很了解)。

后缀表达式是将运算符放在操作数后面,其能使表达式求值变得轻松。

前缀和后缀表示法有三项公共特征:

(1)操作数的顺序与等价的中缀表达式操作数的顺序一致

(2)不需要括号

(3)操作符的优先级不相关

像中缀表达式(20+3)*5写成后缀表达式为20 3 + 5 * 

正式由于后缀的特征使其能用栈来实现求值

算法:

设置一个栈,开始时栈为空,开始扫描字符串,若遇到操作数则入栈;若遇到运算符则从栈中弹出两个操作数先退出的放到运算符的右边,后退出的放到运算左边,运算后再入栈,直到表达式扫描完毕。 此时栈中只剩下一个元素则为计算结果。     

下为其实现的代码:

栈(没写完)

public class StackX {
	private Float theStack[];
	private int maxSize;
	private int top;

	public StackX(int size) {
		theStack = new Float[size];
		maxSize = size;
		top = -1;
	}

	public Float pop() {
		return theStack[top--];
	}

	public void push(Float d) {
		theStack[++top] = d;
	}

	public int size() {
		return top + 1;
	}
}

 计算部分

public class ParsePost {
	private StackX stack;
	private String input;

	public ParsePost(String in) {
		input = in;
	}

	public Float doParse() {
		stack = new StackX(20);
		Float num1, num2, result;
		int t = 0;//用于寻找两个操作数中' '字符
		String temp;
		char ch;
		while (true) {
			t = input.indexOf(' ');
			if (t == -1) {
				break;
			}
			//获取操作数
			temp = input.substring(0, t);
			if (temp.contains("+") || temp.contains("-") || temp.contains("*")
					|| temp.contains("/")) {
				ch = temp.charAt(0);
				//弹出元素进行计算
				num2 = stack.pop();
				num1 = stack.pop();
				switch (ch) {
				case '+':
					result = num1 + num2;
					break;
				case '-':
					result = num1 - num2;
					break;
				case '*':
					result = num1 * num2;
					break;
				case '/':
					result = num1 / num2;
					break;
				default:
					result = (float) 0;
				}
				//计算结果入栈
				stack.push(result);
			} else {
				stack.push(Float.parseFloat(temp));
			}
			input = input.substring(t + 1, input.length());
		}
		return stack.pop();
	}
}

 下部分将介绍如何将中缀表达式变为后缀表达式

猜你喜欢

转载自suc123.iteye.com/blog/2038522