原理:
- 数:入栈
- ‘(’:入栈
- ‘)’:运算符出栈,直到’(‘和’)'匹配
- 运算符:
①:当前符优先级>栈顶符优先级:入栈
②:当前符优先级<=栈顶符优先级:栈内运算符出栈,运算后进栈,再比较
其中 */优先级大于±
代码如下:
先建compute.h头文件
#pragma once
double Compute(char* str);//计算
bool IsOp(char c);//判断是否为运算符
int CompareOp(char str, char sta); //判断运算符优先级,1入栈,0出栈,-1匹配
再建compute.cpp文件
#include "compute.h"
#include<stack>
#include<iostream>
using namespace std;
double Compute(char * str)
{
stack <double> numStack;
stack <char> opStack;
for (int i = 0; str[i] != '\0'; i++)
{
if (!IsOp(str[i])) //不是运算符,入栈
{
if(i==0|| IsOp(str[i-1]))//个位数,入栈
numStack.push((str[i]-48));//ASCII码转换
else //非个位数
{
double result = numStack.top() * 10 + (str[i] - 48);
numStack.pop();
numStack.push(result);
}
}
else//运算符,比较优先级
{
if(opStack.empty())//操作符空栈,直接进栈
opStack.push(str[i]);
else if (CompareOp(str[i],opStack.top())==1)//优先级大,进栈
{
opStack.push(str[i]);
}
else if(CompareOp(str[i], opStack.top()) == 0)//优先级小,栈内运算符出栈,运算后进栈,再比较
{
while (!opStack.empty()&&CompareOp(str[i], opStack.top()) == 0)
{
double num1,num2,result;
char opchar;
opchar =opStack.top();//出栈操作符
opStack.pop();
num2 = numStack.top();//出栈运算数2
numStack.pop();
num1 =numStack.top();//出栈运算数1
numStack.pop();
//运算
if (opchar == '+')
result = num1 + num2;
else if (opchar == '-')
result = num1 - num2;
else if (opchar == '*')
result = num1 * num2;
else if (opchar == '/')
result = num1 / num2;
numStack.push(result);//入栈
};
if (opStack.empty())//栈内无运算符,直接进栈
opStack.push(str[i]);
else if (CompareOp(str[i], opStack.top())==1)//优先级高,入栈了
opStack.push(str[i]);
else //匹配上'(','('出栈
opStack.pop();
}
else //匹配上'(','('出栈
opStack.pop();
}
}
while (!opStack.empty())
{
double num1, num2, result;
char opchar;
opchar = opStack.top();//出栈操作符
opStack.pop();
num2=numStack.top();//出栈运算数2
numStack.pop();
num1=numStack.top();//出栈运算数1
numStack.pop();
//运算
if (opchar == '+')
result = num1 + num2;
else if (opchar == '-')
result = num1 - num2;
else if (opchar == '*')
result = num1 * num2;
else if (opchar == '/')
result = num1 / num2;
numStack.push(result);//入栈
}
return numStack.top();
}
bool IsOp(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' )
return true;
else
return false;
}
int CompareOp(char str, char sta)
{ //1入栈,0出栈,-1匹配
if (sta==NULL) //判断,相等先出栈
return 1;
else if (str == '(') //判断 "("
return 1;
else if (str == '+' || str == '-') //判断 "+-"
{
if (sta == '(')
return 1;
else
return 0;
}
else if (str == '*' || str == '/') //判断 "*/"
{
if (sta != '*'&& sta != '/')
return 1;
else
return 0;
}
else //判断 ")"
{
if (sta == '(')//匹配
return -1;
else
return 0;
}
}
例:
#include "compute.h"
#include<stack>
#include<iostream>
using namespace std;
int main() {
cout<<Compute("23-2*(6/4)+1");
getchar();
return 0;
}
得:21
PS:输入数据不支持小数