计算器-前缀表达式

该程序使用C++编写,能将输入的中缀表达式转换为前缀表达式,并进行计算。它利用栈数据结构处理括号和运算符的优先级,实现了从后缀表达式到前缀表达式的转换,并通过另一个函数进行数值计算。
摘要由CSDN通过智能技术生成
#include<string>
#include<stack>
#include <iostream>
#include<cmath>

using namespace std;

const int N = 6;
pair<char, int>priority[N];

void set_pair() {
	priority[0] = make_pair(')', 0);
	priority[1] = make_pair('(', 0);
	priority[2] = make_pair('+', 1);
	priority[3] = make_pair('-', 1);
	priority[4] = make_pair('*', 2);
	priority[5] = make_pair('/', 2);
}

int find(char ch) {
	for (int i = 0; i < N; i++) {
		if (priority[i].first == ch) {
			return priority[i].second;
		}
	}
}

string prefix() {
	string str, ans;
	stack<char>sign;
	int cnt = 0;
	cin >> str;
	reverse(&str[0], &str[0] + str.size());
	for (int i = 0; i < str.size(); i++) {
		if (isdigit(str[i]) == 0) {
			if (str[i] == '(') {
				while (sign.top() != ')' && !sign.empty()) {
					ans += sign.top();
					sign.pop();
				}
				if (sign.top() == ')') {
					sign.pop();
				}
			}
			else if (str[i] == ')') {
				sign.push(str[i]);
			}
			else {
				while (!sign.empty() && find(sign.top()) > find(str[i])) {
					ans += sign.top();
					sign.pop();
				}
				sign.push(str[i]);
			}
		}
		else {
			string s;
			while (isdigit(str[i]) != 0||str[i]=='.') {
				s += str[i];
				i++;
			}
			ans += s;
			ans += " ";
			i--;
		}
	}
	while (!sign.empty()) {
		ans += sign.top();
		sign.pop();
	}
	reverse(&ans[0], &ans[0] + ans.size());
	cout << ans;
	return ans;
}

double calnum(string str, int i) {
	double n = 0, p;
	int cnt = 0;
	bool b = 0;
	while (i >= 0 && (isdigit(str[i]) != 0 || str[i] == '.')) {
		if (str[i] == '.') {
			i--;
			b = 1;
			continue;
		}
		if (b == 0) {
			cnt++;
		}
		i--;
	}
	i++;
	p = pow(10, cnt - 1) * 1.0;
	while(isdigit(str[i]) != 0 || str[i] == '.'){
		if (str[i] == '.') {
			i++;
			continue;
		}
		n += (str[i] - '0') * p;
		p /= 10;
		i++;
	}
	return n;
}

double calculat(string str) {
	stack<double>num;
	for (int i = str.size() - 1; i >= 0; i--) {
		if (isdigit(str[i]) == 0) {
			double n;
			switch (str[i]) {
			case '+':n = num.top(); num.pop(); n += num.top(); break;
			case '-':n = num.top(); num.pop(); n -= num.top(); break;
			case '*':n = num.top(); num.pop(); n *= num.top(); break;
			case '/':n = num.top(); num.pop(); n /= num.top(); break;
			default:continue;
			}
			num.pop();
			num.push(n);
		}
		else {
			double  n = calnum(str, i);
			num.push(n);
			while (i >= 0 && (isdigit(str[i]) != 0 || str[i] == '.')) {
				i--;
			}
		}
	}
	return num.top();
}

int main() {
	set_pair();
	while (1) {
		string s = prefix();
		cout << "\n" << calculat(s) << "\n\n";
	}
	return 0;
}

献上拙作,欢迎指正。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值