设计一个程序,对输入的以#为结束的算术表达式(包括+,-,,/,(,) ),首先判断表达式是否含有非法字符(即非+,-,,/, (,) 之外的字符),
如果含有非法字符,则报错误信息;
如果正确,计算并输出这个表示式的值。
本题希望利用算符优先关系,实现对算术四则混合运算表达式的求值。
同学学号报一下
你第一个都写完了?
求第一题答案
#include<iostream>
#include<string>
#include<stack>
using namespace std;
stack<char> ch;
stack<int> in;
string str;
int main() {
int x;
cin >> str;
for(int i=0; i<str.length()-1; i++){
x=0;
while(str[i]>='0'&&str[i]<='9'){
x=x*10+str[i]-'0';
i++;
}
if(x) in.push(x);
if(str[i]!='#'){
if(str[i]=='*'||str[i]=='/'||str[i]=='('||ch.empty())
ch.push(str[i]);
else if(str[i]=='+'||str[i]=='-'){
while(str[i]!='*'&&str[i]!='/'){
if(str[i]=='*'){
int a;
a=in.top();
in.pop();
in.top()*=a;
}
else if(str[i]=='/'){
int a;
a=in.top();
in.pop();
in.top()/=a;
}
}
ch.push(str[i]);
}
else if(str[i]==')'){
while(ch.top()!='('){
if(str[i]=='*'){
int a;
a=in.top();
in.pop();
in.top()*=a;
}
else if(str[i]=='/'){
int a;
a=in.top();
in.pop();
in.top()/=a;
}
else if(str[i]=='+'){
int a;
a=in.top();
in.pop();
in.top()+=a;
}
else if(str[i]=='-'){
int a;
a=in.top();
in.pop();
in.top()-=a;
}
}
ch.pop();
}
}
}
while(!ch.empty()){
if(ch.top()=='*'){
int a;
a=in.top();
in.pop();
in.top()*=a;
}
else if(ch.top()=='/'){
int a;
a=in.top();
in.pop();
in.top()/=a;
}
else if(ch.top()=='+'){
int a;
a=in.top();
in.pop();
in.top()+=a;
}
else if(ch.top()=='-'){
int a;
a=in.top();
in.pop();
in.top()-=a;
}
ch.pop();
}
cout << in.top() << endl;
//return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: