简单四则运算

/*问题描述:
输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值
注:
1、表达式只含 + , -, *, / 四则运算符,不含括号
2、表达式数值只包含个位整数(0 - 9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8 / 3 = 2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,除此之外不含其它任何字符,不会出现计算溢出情况
要求实现函数:
int calculate(int len, char *expStr)
输入:int len : 字符串长度;char* expStr : 表达式字符串;
输出:无
返回:计算结果*/
#include <iostream>
#include <cctype>
using namespace std;
int calculate(int len, char*expstr)
{
	int result=0;
	int *suffix = new int[len];                  //表示中缀表达式
	int j = 0;
	int priority = -1;                           //记录栈顶元素的优先级,初始为-1
	int table[] = { 0, 0, 2, 1, 0, 1, 0, 2 };    //表示操作符的优先级
	int *stack=new int[len];                     //模拟栈
	int top = -1;                                //栈顶
	//中缀表达式转换成后缀表达式
	for (int i = 0; i < len; i++)
	{
		//如果是数字,把数字压入到中缀表达式中
		if (isdigit(expstr[i]))
		{
			suffix[j] = expstr[i]-'0';              //不要忘记减'0'
			j++;
		}
		//如果是操作符,把操作符压入栈中
		else
		{
			//如果当前操作符优先级不大于栈顶元素的优先级,则先出栈到后缀表达式中再入栈
			while (priority >= table[expstr[i] % 10])
			{
				suffix[j] = stack[top];
				j++;
				top--;
				//出栈之后保存新的栈顶元素的优先级
				if (top != -1)
					priority = table[stack[top] % 10];
				else
					priority = -1;
			}
			//直到栈顶元素的优先级小于当前操作符优先级,入栈
			top++;
			stack[top] = expstr[i];
			priority = table[stack[top] % 10];
		}
	}
	//如果栈不为空,则把栈中的操作符都存到后缀表达式中
	while (top != -1)
	{
		suffix[j] = stack[top];
		top--;
		j++;
	}
	//计算后缀表达式,挨个扫描后缀表达式的元素
	for (int i = 0; i < j; i++)
	{
		switch (suffix[i])
		{
		case 42:
			result = stack[top - 1] * stack[top];
			top--;
			stack[top] = result;
			break;
		case 43:
			result = stack[top - 1] + stack[top];
			top--;
			stack[top] = result;
			break;
		case 45:
			result = stack[top - 1] - stack[top];
			top--;
			stack[top] = result;
			break;
		case 47:
			result = stack[top - 1] / stack[top];
			top--;
			stack[top] = result;
			break;
		default:
			top++;
			stack[top] = suffix[i];
			break;
		}
	}
	return result;
}
int main()
{
	int len;
	cin >> len;
	char*expstr = new char[len];
	for (int i = 0; i < len; i++)
	{
		cin >> expstr[i];
	}
	cout << calculate(len, expstr) << endl;
	return 0;
}

附上cctype库中的函数,参数类型为char型。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值