C++ 实现计算器

说明:

用C++写的计算器,利用堆栈将中缀表达式转为后缀表达式实现,不支持带括号的计算

输入格式:

中序表达式加‘=’号

3.8+4.69*5.7-8.7/2.1=

输出结果:

26.3901

代码:

#include <iostream>
#include <stack>

using namespace std;

double inStack();   //核心函数,将操作符有序的入栈计算, 最后返回结果
void calculate(stack<char>& Ope, stack<double>& Num);  //用来计算加减乘除, 结果放在数字栈顶
int priority(char ope_);   //用来计算操作符的优先级

int main() {
	double result;   //最后的结果

	cout << "请输入:\n";
	result = inStack();   //将缓冲区的操作符和数字压入栈 

	cout <<"结果是:\n"<< result;

	return 0;
}

double inStack() {
	stack<char> Ope; char ope_;
	stack<double> Num; 	double num_;
	
	while (1) {
		cin >> num_ >> ope_;   //不带括号的计算,数字与符号是间隔排列的
		Num.push(num_);   //数字直接入栈

		if (ope_ == '=') {
			while (!Ope.empty()) calculate(Ope, Num); //如果符号栈不空,就一直计算
			return Num.top();  //如果是等号且符号栈顶为空,就返回数字栈顶元素
		}
		else if (Ope.empty()) Ope.push(ope_);    //压入符号
		else if (priority(Ope.top()) >= priority(ope_)) {  //如果栈顶符号的优先级大于等于当前
			calculate(Ope, Num);   //计算结果压入数字栈,取出当前栈顶
			Ope.push(ope_);  //压入当前符号
		}
		else Ope.push(ope_);  //否则就压入符号栈
	}
}

void calculate(stack<char>& Ope, stack<double>& Num) {
	double a, b;
	a = Num.top(); Num.pop();
	b = Num.top(); Num.pop();

	if (Ope.top() == '+') Num.push(b + a);
	else if (Ope.top() == '-') Num.push(b - a);
	else if (Ope.top() == '*') Num.push(b * a);
	else if (Ope.top() == '/') Num.push(b / a);

	Ope.pop();
}

int priority(char ope_) {
	if (ope_ == '+' || ope_ == '-') return 1;
	else if (ope_ == '*' || ope_ == '/') return 2;
}

参考文章:

中缀表达式转换前缀表达式和后缀表达式

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

积木41

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值