算法训练 表达式计算

问题描述
  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
  输入一行,包含一个表达式。
输出格式
  输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。


问题分析:利用双栈一个存储运算符一个存储数字,这里计算的方法是中缀表达式转换成后缀表达式

                就是比如一个式子1+2*3-4时,在*号入栈事,我们要先考虑前面的数字1,2要不要计算,这里就要有优先级问题,如果现在的符号是×或者÷,那么符号栈里的前一个符号,也就是top,必须也要是×或者÷这样才能把前两个数字计算出值,而如果现在的符号是+,-,那么前面任何符号,除了‘(’都可以计算。


#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<string>
#include<algorithm> 
#include<stack>
using namespace std;

stack<int>stack_num;
stack<char>stack_ch;
char str[110];
char num[110];

void com_all()		//对于+,-,前面是+——*/都不影响前面的结果,可以先计算前面的 
{
	int num1,num2;
	
	while(stack_ch.top() != '('){
		num1 = stack_num.top();
		stack_num.pop();
		num2 = stack_num.top();
		stack_num.pop();
		
		switch(stack_ch.top()){
			case '+':
				num2 += num1;
				break;
			case '-':
				num2 -= num1;	//num1为后面的数,num2为前面的数,不能随意,否则减法除法会出错
				break;
			case '*':
				num2 *= num1;
				break;
			case '/':
				num2 /= num1;
				break;
		}
		stack_num.push(num2);
		stack_ch.pop();
	}
}

void com_mul_dev()
{
	int num1,num2;
	
	while(stack_ch.top() == '*' || stack_ch.top() == '/'){	//当现在为乘除时,前面为乘除才不会影响计算,只有乘除优先级大于等于乘除 
		num1 = stack_num.top();
		stack_num.pop();
		num2 = stack_num.top();
		stack_num.pop();
		
		switch(stack_ch.top()){
			case '*':
				num2 *= num1;
				break;
			case '/':
				num2 /= num1;
				break;
		}
		stack_num.push(num2);
		stack_ch.pop();
	}
}

int main()
{
	int k = 0;
	cin >> str;
	stack_ch.push('(');	//作为最后一个计算的结束 
	strcat(str,".");	//要加一个标识符结尾,否则如果是1-2+3*(4-5)这样不能计算完 
	for(int i = 0; i < strlen(str); i++){
		if (str[i] >= '0' && str[i] <= '9'){
			num[k++] = str[i];
			continue;
		}
		num[k] = 0;
		if (num[0] != 0){
			int n = atoi(num);
			num[0] = 0;
			stack_num.push(n);
			k = 0;
		}
		
		switch(str[i]){
			case '+':
				com_all();
				stack_ch.push('+');
				break;
			case '-':
				com_all();
				stack_ch.push('-');
				break;
			case '*':
				com_mul_dev();
				stack_ch.push('*');
				break;
			case '/':
				com_mul_dev();
				stack_ch.push('/');
				break;
			case '(':
				stack_ch.push('(');
				break;
			case ')':
				com_all();
				stack_ch.pop();		//把'('pop出去 
				break;
			case '.':
				com_all();
				stack_ch.pop();
				break;
			default:	break;
		} 
		
	}
	printf("%d",stack_num.top());
		
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值