hdoj 1237
表达式求值 by 两个栈
起初Runtime Error(ACCESS_VIOLATION) 最后参考了这篇博客 特别要注意0
满满的都是细节 也是很艰辛
//hdoj 1237 表达式求值
#include <stdio.h>
#include <stack>
#include <string.h>///strcmp
#include <sstream>///stringstream stream;好用!!!
using namespace std;
const int maxn=200;
int main(){
char expr[maxn]={0};
while(gets(expr),strcmp(expr,"0")!=0){//自动以0结尾?!//scanf遇到到空格就结束了! //expr!="0"不行 停不下来
//printf("%s\n",expr);///打印字符串的方式?! 参数为首地址!!!!
stack<double> num;
stack<char> op;
int p=0;
while(expr[p]!=0){
//printf("%c\n",expr[p]);///是%c 不能用%s
if(expr[p]==' ') {
++p;
}
else if(expr[p]>='0'&&expr[p]<='9'){/// 0
string number="";
while(expr[p]>='0'&&expr[p]<='9'){/// 0
//number.push_back(expr[p]);//void push_back (char c);
number+=expr[p];//both ok!字符串末尾添加字符的方式
++p;//
}
//printf("%s\n",&number[0]);////////打印字符串的方式?! 参数为首地址!!!!
double number_double;
stringstream stream;// yes!
stream<<number;
stream>>number_double;
//sscanf(&number[0],"%lf",&number_double);//yes!之前少了一个取址符& !!!
num.push(number_double);
}
else{
if(op.empty()) {
op.push(expr[p]);
}
else{
char c=op.top();
while(c=='*'||c=='/'||((c=='+'||c=='-')&&(expr[p]=='+'||expr[p]=='-'))) {
op.pop();
//op.push(expr[p]);//不能直接放!
double a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
if(c=='*') num.push(a*b);
else if(c=='/') num.push(a/b);
else if(c=='+') num.push(a+b);
else if(c=='-') num.push(a-b);
if(op.empty())///////
break;
else c=op.top();
}
op.push(expr[p]);////
}
++p;
}
}
//计算!!!
while(!op.empty()){
char c=op.top();
op.pop();
double a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
if(c=='*') num.push(a*b);
else if(c=='/') num.push(a/b);
else if(c=='+') num.push(a+b);
else if(c=='-') num.push(a-b);
}
printf("%.2lf\n",num.top());
/*没用到 因为输入时自动以0结尾 ?
memset(expr,'\0',maxn);//extern void *memset(void *buffer, int c, int count);
//把buffer所指内存区域的前count个字节设置成字符c。 说明:返回指向buffer的指针。
//memset(buffer, 0, sizeof(buffer));*/
}
return 0;
}