第三题、条件表达式求值
描述: 给定一个以字符串形式表示的算术表达式,计算该表达式的值。
表达式支持如下运算:“+、-、*、/”,其中“*”和“/”的优先级要高于“+”和“-”;
不需要考虑括号,且表达式之间没有空格;
例如:对于表达式"3-2+15*2",该表达式值为31.
运行时间限制: 60 Sec
内存限制: 256 MByte
输入: 加减乘除四则运算表达式,长度不超过1024字节,运算式中不含有括号和空格。
输出: 表达式的运算结果。
样例输入: 3-2+15*2
描述: 给定一个以字符串形式表示的算术表达式,计算该表达式的值。
表达式支持如下运算:“+、-、*、/”,其中“*”和“/”的优先级要高于“+”和“-”;
不需要考虑括号,且表达式之间没有空格;
例如:对于表达式"3-2+15*2",该表达式值为31.
运行时间限制: 60 Sec
内存限制: 256 MByte
输入: 加减乘除四则运算表达式,长度不超过1024字节,运算式中不含有括号和空格。
输出: 表达式的运算结果。
样例输入: 3-2+15*2
样例输出: 31
#include "iostream"
#include "string"
#include "stack"
using namespace std;
char Precede(char ch1,char ch2)
{
if ((ch2 =='*'||ch2 =='/')&&(ch1 =='+'||ch1 =='-'))
{
return '>';
}
else
return '<';
}
void calulate(char op,int num1,int num2,stack<int>& digit)
{
int temp;
switch(op)
{
case '+':
temp =num2 +num1;
break;
case '-':
temp =num2 -num1;
break;
case '*':
temp =num2 *num1;
break;
case '/':
temp =num2 /num1;
break;
}
digit.push(temp);
}
void cal(char* input)
{
int len =strlen(input);
stack<char> oper;
stack<int> digit;
int k=0;
int sum =0;
while(k<len)
{
if(input[k]>'0'&& input[k]<'9')
{
sum =0;
while(input[k]>'0'&&input[k]<'9')
{
sum =sum*10 +input[k] -'0';
k++;
}
digit.push(sum);
}
else
{
if (oper.empty())
{
oper.push(input[k]);
k++;
}
else
{
if (Precede(oper.top(),input[k]) =='>')//如果输入的操作符的优先级大,则字符操作符入栈
{
oper.push(input[k]);
k++;
}
else
{
int temp;
int num1 =digit.top();
digit.pop();
int num2 =digit.top();
digit.pop();
char op =oper.top();
oper.pop();
calulate(op,num1,num2,digit);
}
}
}
}
while(!oper.empty())
{
int temp;
int num1 =digit.top();
digit.pop();
int num2 =digit.top();
digit.pop();
char op =oper.top();
oper.pop();
calulate(op,num1,num2,digit);
}
cout<<digit.top()<<endl;
}
void main()
{
char input[20];
cin>>input;
cal(input);
}