结构与算法 7-21 求前缀表达式的值 (30行精简)

7-21 求前缀表达式的值 (25 分)

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。

输入格式:

输入在一行内给出不超过30个字符的前缀表达式,只包含+-*/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。

输出格式:

输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR

输入样例:

+ + 2 * 3 - 7 4 / 8 4

输出样例:

13.0

递归版:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool isNumber(const string& str) {	//判断字符串是否为数字
	istringstream sin(str);
	double test;
	return sin >> test && sin.eof();
}
double calc() {
	string str;
	cin >> str;
	if (isNumber(str))
		return stod(str);
	switch (str[0]){
	case '+':	return calc() + calc();
	case '-':	return calc() - calc();
	case '*':	return calc() * calc();
	case '/':
		double a = calc(), b = calc();
		if (b == 0) {
			cout << "ERROR" << endl;
			exit(0);
		}
		return a / b;
	}
}
int main() {
	printf("%0.1lf\n", calc());
	return 0;
}

 非递归版:

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;
bool isNumber(const string& str) {	//判断字符串是否为数字
	istringstream sin(str);
	double test;
	return sin >> test && sin.eof();
}
int main() {
	string str;
	vector<string> exp;
	while (cin >> str) {
		exp.push_back(str);
		if (getchar() == '\n')
			break;
	}
	double a, b;
	vector<double> result;
	reverse(exp.begin(), exp.end());
	for (string& str : exp) {
		if (isNumber(str))
			result.push_back(stod(str));
		else {
			a = result.back(); result.pop_back();
			b = result.back(); result.pop_back();
			if (str == "+")		result.push_back(a + b);
			else if (str == "-")	result.push_back(a - b);
			else if (str == "*")	result.push_back(a * b);
			else {
				if (b == 0) {
					cout << "ERROR" << endl;
					return 0;
				}
				result.push_back(a / b);
				
			}
		}
	}
	printf("%0.1lf", result.back());
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值