给出一个表达式,求取表达式的值

给出一个表达式,求取表达式的值

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stack>
using namespace std;
/***
思路:
1.字符串预处理,针对可能出现的“{,},[,],-”等特殊情况进行替换,判断‘-’是负号还是减号,负号前面+0,转变成减法运算
2.将中缀字符串转变为后缀字符串数组
3.对后缀字符串数组进行求解
***/
int main(int argc, char const *argv[])
{
	string str;
	while(getline(cin,str))
		calcExp(str);
	return 0;
}
void calcExp(string &str){
	preProcess(str);
	vector<string>vstr=mid2post(str);
	double res=calcPostExp(vstr);
	cout<<res<<endl;
}
/***
对字符串进行预处理:
1.将‘{、}、[,]’替换成'()'
2.将'-'前面添加0转变成减法运算
***/
void preProcess(string &str){
	int num=str.size();
	for(int i=0;i<num;i++){
		if(str[i]=='{')
			str[i]='(';
		else if (str[i]=='}')
			str[i]=')';
		else if(str[i]=='[')
			str[i]='(';
		else if(str[i]==']')
			str[i]=')';
		else if(str[i]=='-'){
			if(i==0)
				str.insert(0,1,'0');
			else if(str[i-1]=='(')
				str.insert(i,1,'0');
		}

	}
}
//中缀转后缀
vector<string>& mid2post(string &str){
	vector<string>vstr;
	satck<char>cstack;
	string temp="";
	//扫描字符串
	for(int i=0,n=str.size();i<n;i++){
		temp="";
		//若为数字
		if(str[i]>='0'&&str[i]<='9'){
			temp+=str[i];
			while(i+1<n&&str[i+1]>='0'&&str[i+1]<='9'){
				temp+=str[i+1];
				i++;
			}
			vstr.push_back(temp);
		}
		//栈空或遇见字符'('
		else if(cstack.empty()||str[i]=='(')
			cstack.push(str[i]);
			//若栈顶优先级高
		else if(cmpPriority(cstack.top(),str[i])){
			//当前字符为')',栈中元素出栈,入字符串数组中,直到遇到'('
			if(str[i]==')'){
				while(!cstack.empty()&&cstack.top()!='('){
					temp+=cstack.top();
					cstack.pop();
					vstr.push_back(temp);
					temp=""
				}
				cstack.pop();
			}
			//栈中优先级高的元素出栈,入字符串数组,直到优先级低于当前字符
			else{
				while(!cstack.empty()&&cmpPriority(cstack.top(),str[i])){
					temp+=cstack.top();
					cstack.pop();
					vstr.push_back(temp);
					temp="";
				}
				cstack.push(str[i]);
			}
		}
		//当前字符优先级高于栈顶元素,直接入栈
		else
			cstack.push(str[i]);	
	}
	//栈中还存在运算符时:出栈,存入字符串数组
	while(!cstack.empty){
		temp+=cstack.top();
		cstack.pop();
		vstr.push_back(temp);
		temp="";
	}
	return vstr;
}

//比较当前字符与栈顶字符的优先级,若栈顶高,返回true
bool cmpPriority(char top,char cur){
	if((top=='+'||top=='-')&&(cur=='+'||cur=='-'))
		return true;
	if((top=='*'||top=='/')&&(cur=='+' || cur=='-'|| cur=='*' || cur=='/'))
		return true;
	if(cur==')')
		return true;
	return false;
}
//对后缀表达式进行求值:主要是根据运算符取出两个操作数进行运算
double calcPostExp(vector<string>&vstr){
	stack<double>opstack;
	int num,op1,op2;
	string temp="";
	stringstream ss;
	for(int i=0,n=vstr.size();i<n;i++){
		temp=vstr[i];
		//如果当前字符串是数字,利用字符串流转化为int型
		if(temp[0]>='0'&&temp[0]<='9'){
			ss<<temp;//通过流将数值转为字符串,或将字符串转为数值。
			ss>>num;
			opstack.push(num);
		}
		//若是操作符,取出两个操作数,进行运算,并将结果存入
		else if(vstr[i]=='+'){
			op2=opstack.top();
			opstack.pop();
			op1=opstack.top();
			opstack.pop();
			opstack.push(op1+op2);
		}
		else if(vstr[i]=='-'){
			op2=opstack.top();
			opstack.pop();
			op1=opstack.top();
			opstack.pop();
			opstack.push(op1-op2);
		}
		else if(vstr[i]=='*'){
			op2=opstack.top();
			opstack.pop();
			op1=opstack.top();
			opstack.pop();
			opstack.push(op1*op2);
		}
		else if(vstr[i]=='/'){
			op2=opstack.top();
			opstack.pop();
			op1=opstack.top();
			opstack.pop();
			opstack.push(op1+op2);
		}
	}
	return opstack.top();
}

 

以下是用C语言实现算术表达式求值的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_SIZE 100 // 定义一个栈结构体 typedef struct { int top; // 栈顶指针 int data[MAX_SIZE]; // 栈数据 } Stack; // 初始化栈 void init(Stack *s) { s->top = -1; } // 判断栈是否为空 int is_empty(Stack *s) { return s->top == -1; } // 判断栈是否已满 int is_full(Stack *s) { return s->top == MAX_SIZE - 1; } // 入栈 void push(Stack *s, int x) { if (is_full(s)) { printf("Stack overflow!\n"); exit(1); } s->data[++s->top] = x; } // 出栈 int pop(Stack *s) { if (is_empty(s)) { printf("Stack underflow!\n"); exit(1); } return s->data[s->top--]; } // 取栈顶元素 int peek(Stack *s) { if (is_empty(s)) { printf("Stack underflow!\n"); exit(1); } return s->data[s->top]; } // 判断是否为操作符 int is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 判断操作符优先级 int precedence(char c) { if (c == '+' || c == '-') { return 1; } else if (c == '*' || c == '/') { return 2; } else { return 0; } } // 计算两个数的结果 int calculate(int a, int b, char op) { int result = 0; switch(op) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': if (b == 0) { printf("Error: division by zero!\n"); exit(1); } result = a / b; break; default: printf("Error: invalid operator!\n"); exit(1); } return result; } // 计算算术表达式的结果 int evaluate(char *expr) { Stack op_stack; // 操作符栈 Stack val_stack; // 数字栈 init(&op_stack); init(&val_stack); int len = strlen(expr); int i, j, k, num, a, b, result; char c, op; for (i = 0; i < len; i++) { c = expr[i]; if (isdigit(c)) { // 如果是数字,则一直读取到下一个非数字字符 num = 0; j = i; while (isdigit(expr[j])) { num = num * 10 + (expr[j] - '0'); j++; } i = j - 1; push(&val_stack, num); } else if (is_operator(c)) { // 如果是操作符,则将其与操作符栈顶元素比较优先级 while (!is_empty(&op_stack) && precedence(c) <= precedence(peek(&op_stack))) { a = pop(&val_stack); b = pop(&val_stack); op = pop(&op_stack); result = calculate(b, a, op); push(&val_stack, result); } push(&op_stack, c); } else if (c == '(') { push(&op_stack, c); } else if (c == ')') { // 如果是右括号,则计算括号内的表达式结果 while (peek(&op_stack) != '(') { a = pop(&val_stack); b = pop(&val_stack); op = pop(&op_stack); result = calculate(b, a, op); push(&val_stack, result); } pop(&op_stack); } else { printf("Error: invalid character!\n"); exit(1); } } // 处理剩余的操作符 while (!is_empty(&op_stack)) { a = pop(&val_stack); b = pop(&val_stack); op = pop(&op_stack); result = calculate(b, a, op); push(&val_stack, result); } // 返回最终结果 return pop(&val_stack); } int main() { char expr[MAX_SIZE]; printf("Enter an arithmetic expression: "); fgets(expr, MAX_SIZE, stdin); int result = evaluate(expr); printf("Result: %d\n", result); return 0; } ``` 示例输入: ``` (1+2)*3-4/2 ``` 示例输出: ``` Result: 7 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值