表達式樹求四則運算

表達式樹求四則運算 ,參考lrj。有空補一個逆波蘭表達式求法

 

string s;
double build_tree(int x,int y){
	if (y - x == 1)
		return s[x] - '0';
	int p = 0;//num of '(', ')'
	int c1 = -1, c2 = -1;
	for (int i = x; i < y; i++) {
		switch (s[i]) {
		case'(':p++; break;
		case')':p--; ; break;
		case'+':case'-': if (!p)c1 = i; break;
		case'*':case'/': if (!p)c2 = i; break;
		}
	}
	if (c1 < 0)c1 = c2;
	if (c1 < 0)	return build_tree(x + 1, y - 1);
	double a = build_tree(x, c1);
	double b = build_tree(c1 + 1, y);
	if (s[c1] == '+')
		return a + b;
	if (s[c1] == '-')
		return a - b;
	if (s[c1] == '*')
		return a * b;
	if (s[c1] == '/')
		return a / b;
	return 0x3f3f3f3f;
}

int main()
{
	cin >> s;
	cout << build_tree(0, size(s)) << endl;
	cout << 1+(7-3*3.0/2)*7 << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章