【C++】C++表达式求值,加、减、乘、除、括号优先级

1.算法核心是合成符号优先级的二维数组。话不多说,代码先行。

#include<iostream>
#include<cstring>//字符串
#include<cstdio>//输入和输出库
#include<cctype>//定义了有关字符判断与处理的库函数
#include<stack>//栈的引用
#define PLUS 0//+
#define MINUS 1//-
#define POWER 2//*
#define DIVIDE 3///
#define LEFTP 4//(
#define PIGHP 5//)
#define STARTEEND 6//#
using namespace std;
stack<char> opter;    //运算符栈
stack<double> opval;  //操作数栈

int getindex(char theta)   //获取theta所对应的索引
{
	int index = 0;
	switch (theta)
	{
	case '+':
		index = 0;
		break;
	case '-':
		index = 1;
		break;
	case '*':
		index = 2;
		break;
	case '/':
		index = 3;
		break;
	case '(':
		index = 4;
		break;
	case ')':
		index = 5;
		break;
	case '#':
		index = 6;
	default:break;
	}
	return index;
}

char getpriority(char theta1, char theta2)   //获取theta1与theta2之间的优先级
{
	const char priority[][7] =     //算符间的优先级关系
	{
		{ '>','>','<','<','<','>','>' },
		{ '>','>','<','<','<','>','>' },
		{ '>','>','>','>','<','>','>' },
		{ '>','>','>','>','<','>','>' },
		{ '<','<','<','<','<','=','0' },
		{ '>','>','>','>','0','>','>' },
		{ '<','<','<','<','<','0','=' },
	};

	int index1 = getindex(theta1);
	int index2 = getindex(theta2);
	return priority[index1][index2];//返回级别关系
}

double calculate(double b, char theta, double a)   //计算b theta a
{
	switch (theta)
	{
	case '+':
		return b + a;
	case '-':
		return b - a;
	case '*':
		return b * a;
	case '/':
		return b / a;
	default:
		break;
	}
}

double getAnswer()//表达式求值
{
	opter.push('#');//首先将'#'入栈opter,push()在栈顶增加元素 (增加)
	int counter = 0;//添加变量counter表示有多少个数字相继入栈,实现多位数的四则运算
	double c = getchar();//字符缓冲
	//int i = 1;//用于小数相加
	while (c != '#' || opter.top() != '#')   //top()是取出栈顶元素,不会删掉栈里边的元素
	{
		int i = 1;//用于小数相加
		if (isdigit(c))   //若参数c为阿拉伯数字0~9,则返回非0值,否则返回0。
		{
			if (counter == 1)   //counter==1表示上一字符也是数字,所以要合并,比如12*12,要算12,而不是单独的1和2
			{
				double t = opval.top();
				opval.pop();//pop() 移除栈顶元素 (删除)
				opval.push(t * 10 + (c - '0'));//字符转数字的时候(如:‘8’ - ‘0’ 的计算结果就是8)
				counter = 1;
			}
			else
			{
				opval.push(c - '0');//将c对应的数值入栈opval
				counter++;//代表此数字为数字
			}
			c = getchar();//重新获取字符
		}
		else if (c == '.' && counter == 1)
		{
			c = getchar();//重新获取字符
			while (isdigit(c))   //若参数c为阿拉伯数字0~9,则返回非0值,否则返回0。
			{
				int j = i;
				if (counter == 1)
				{
					c = (c - '0');
					while (j--)
					{
						c = c * 0.1;
					}
					double t = opval.top();
					t = t + c;
					opval.pop();//pop() 移除栈顶元素 (删除)
					opval.push(t);
					counter = 1;
				}
				c = getchar();//重新获取字符
				i++;
			}
			counter = 0;//counter置零
		}
		else
		{
			counter = 0;//counter置零
			i = 0;//小数个数置零
			switch (getpriority(opter.top(), c))//获取运算符栈opter栈顶元素与c之间的优先级,用'>','<','='表示
			{
			case '<'://<则将c入栈opter
				opter.push(c);
				c = getchar();
				break;
			case '='://=将opter栈顶元素弹出,用于括号的处理
				opter.pop();
				c = getchar();
				break;
			case '>'://>则计算
				char theta = opter.top();
				opter.pop();
				double a = opval.top();
				opval.pop();
				double b = opval.top();
				opval.pop();
				opval.push(calculate(b, theta, a));
			}
		}
	}
	return opval.top();   //返回opval栈顶元素的值
}

int main()//007
{
	int t;     // 需要计算的表达式的个数
	int i = 1;
	cout << "请输入要计算的表达式个数,以#号结束:";
	cin >> t;
	int c = getchar();
	while (t--)
	{
		cout << "请输入第" << i << "个表达式的运算" << endl;
		while (!opter.empty())opter.pop();//empty()判断容器是否为空的函数,释放运算符栈
		while (!opval.empty())opval.pop();//释放操作数栈
		double ans = getAnswer();//输入,得结果
		cout << "结果:";
		cout << ans << endl << endl;
		c = getchar();//获取的下一个项式
		i++;
	}
	system("pause");
	return 0;
}

2.运行结果:注意括号需英文输入。

 小小代码奉上,希望有所帮助。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++逆波兰表达式求值是一种常见的数学表达式求值方法,也被称为后缀表达式求值。逆波兰表达式是一种不需要括号来标识优先级表达式表示方法,它将操作符放在操作数的后面。 在C++中,可以通过使用栈来实现逆波兰表达式求值。具体步骤如下: 1. 创建一个空栈用于存储操作数。 2. 从左到右遍历逆波兰表达式的每个元素。 3. 如果当前元素是操作数,则将其压入栈中。 4. 如果当前元素是操作符,则从栈中弹出两个操作数,并根据操作符进行计算,将计算结果压入栈中。 5. 重复步骤3和步骤4,直到遍历完整个逆波兰表达式。 6. 最后,栈中剩下的唯一元素就是逆波兰表达式的求值结果。 下面是一个示例代码,用于实现逆波兰表达式求值: ```cpp #include <iostream> #include <stack> #include <string> #include <sstream> using namespace std; int evaluateRPN(string expression) { stack<int> operands; stringstream ss(expression); string token; while (getline(ss, token, ' ')) { if (token == "+" || token == "-" || token == "*" || token == "/") { int operand2 = operands.top(); operands.pop(); int operand1 = operands.top(); operands.pop(); if (token == "+") { operands.push(operand1 + operand2); } else if (token == "-") { operands.push(operand1 - operand2); } else if (token == "*") { operands.push(operand1 * operand2); } else if (token == "/") { operands.push(operand1 / operand2); } } else { operands.push(stoi(token)); } } return operands.top(); } int main() { string expression = "5 + 3 *"; int result = evaluatePN(expression); cout << "Result: " << result << endl; return 0; } ``` 以上代码中,我们使用了一个栈来存储操作数,并通过stringstream来逐个读取逆波兰表达式中的元素。如果遇到操作符,则从栈中弹出两个操作数进行计算,并将结果压入栈中。最后,栈中剩下的唯一元素就是逆波兰表达式的求值结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值