NYOJ 35 運算式求值(棧)

來源:互聯網
上載者:User

這些函數中都有“重複”的,因為運算元(OPND)棧用double,操作符(OPTR)棧用char。C++中的模板可以解決這個問題嗎?

 這是對著書寫的:

#include <iostream>using namespace std;#define STACK_INIT_SIZE 100#define STACKINCREMENT 100char Precede_Matrix[7][7] = {{'>', '>', '<', '<', '<', '>', '>',},{'>', '>', '<', '<', '<', '>', '>',},{'>', '>', '>', '>', '<', '>', '>',},{'>', '>', '>', '>', '<', '>', '>',},{'<', '<', '<', '<', '<', '=', '0',},{'>', '>', '>', '>', '0', '>', '>',},{'<', '<', '<', '<', '<', '0', '=',}};char Precede ( char a, char b ){int i = 0;int j = 0;switch (a){case '+' : i = a - '+'; break;case '-' : i = a - '-' + 1; break;case '*' : i = a - '*' + 2; break;case '/' : i = a - '/' + 3; break;case '(' : i = a - '(' + 4; break;case ')' : i = a - ')' + 5; break;case '#' : i = a - '#' + 6; break;default : cout << "Error1!" << endl;}switch (b){case '+' : j = b - '+'; break;case '-' : j = b - '-' + 1; break;case '*' : j = b - '*' + 2; break;case '/' : j = b - '/' + 3; break;case '(' : j = b - '(' + 4; break;case ')' : j = b - ')' + 5; break;case '#' : j = b - '#' + 6; break;default : cout << "Error2!" << endl;}char c = Precede_Matrix[i][j];return c;}int Operate(int a, char oper, int b){switch (oper){case '+': return a + b;case '-': return a - b;case '*': return a * b;case '/': return a / b;default: cout << "Error3!" << endl; return 0;}}struct stack_char{char *base;char *top;int stacksize;}OPTR;struct stack_int{int *base;int *top;int stacksize;}OPND;// 兩位元的只能用int來存?void InitStack(struct stack_char &S){S.base = (char *)malloc( STACK_INIT_SIZE * sizeof(char) );if(!S.base)cout << "Overflow1!" << endl;S.top = S.base;S.stacksize = STACK_INIT_SIZE;}void InitStack(stack_int &S){S.base = (int *)malloc( STACK_INIT_SIZE * sizeof(int) );if(!S.base)cout << "Overflow2!" << endl;S.top = S.base;S.stacksize = STACK_INIT_SIZE;}void Push(stack_char &S, char e){if(S.top - S.base >= S.stacksize)// 判滿{S.base = (char *)realloc( S.base,(S.stacksize + STACKINCREMENT) * sizeof(char) );if(!S.base)cout << "Overflow3!" << endl;S.top = S.base + S.stacksize;S.stacksize += STACKINCREMENT;}* S.top++ = e;}void Push(stack_int &S, int e){if(S.top - S.base >= S.stacksize)// 判滿{S.base = (int *)realloc( S.base, (S.stacksize + STACKINCREMENT) * sizeof(int) );if(!S.base)cout << "Overflow4!" << endl;S.top = S.base + S.stacksize;S.stacksize += STACKINCREMENT;}* S.top++ = e;}void Pop (stack_char &S, char &e){if(S.top == S.base)// 判空cout << "Error4!" << endl;e = * --S.top;}void Pop (stack_int &S, int &e){if(S.top == S.base)// 判空cout << "Error5!" << endl;e = * --S.top;}char GetTop(stack_char S){if (S.top == S.base)// 判空cout << "Error6!" << endl;return *(S.top - 1);}int GetTop(stack_int S){if (S.top == S.base)// 判空cout << "Error7!" << endl;return *(S.top - 1);}int EvaluateExpression(){int a;int b;char x;char theta;InitStack(OPTR);Push(OPTR, '#');InitStack(OPND);char c = getchar();// 輸入若是數字,只能是個位元while ( !(c == '#' && GetTop(OPTR) == '#') ){if ( '0' <= c && c <= '9' )// c is operand{c -= '0';Push(OPND, c);c = getchar();}else// c is operator or delimiter{switch (Precede (GetTop(OPTR), c)){case '<':Push(OPTR, c);c = getchar();break;case '=':Pop(OPTR, x);c = getchar();break;case '>':Pop(OPTR, theta);Pop(OPND, b);Pop(OPND, a);Push(OPND, Operate(a, theta, b));break;default: cout << "Error8!" << endl;}}}//  OPTR棧的棧頂元素和當前讀入的字元均為“#”//  即“#”=“#”時整個運算式求值完畢int result = GetTop(OPND);free(OPTR.base);free(OPND.base);return result;//要在釋放前保留下結果}int main(){cout << EvaluateExpression() << endl;return 0;}

NYOJ上該題的標程:

 #include<stdio.h>#include<string.h>#include<stdlib.h>char str[1005];int start;char s[50],ss[50];int i,j;double Term();double Expression();double Factor();double Term(){    double f=Factor(),t;    --start;    if(str[start]=='*')    {        t=Term();        return t*f;    }    else if(str[start]=='/')    {        t=Term();        return t/f;    }    else {++start;return f;}}double Expression(){    double t=Term(),e;    --start;    if(str[start]=='+')    {        e=Expression();        return e+t;    }    else if(str[start]=='-')    {        e=Expression();        return e-t;    }    else {++start;return t;}}double Factor(){    --start;    double ret;    if(str[start]==')')    {        ret=Expression();        --start;        return ret;    }    else{i=0;memset(ss,0,sizeof(ss));while((str[start]>='0'&&str[start]<='9')||str[start]=='.')s[i++]=str[start--];++start;for(j=0;j<i;j++){ss[j]=s[i-1-j];}return atof(ss);}}int main(){//freopen("1.txt","r",stdin);int n;scanf("%d",&n);while(n--){scanf("%s",str);start=strlen(str)-1;printf("%.2lf\n",Expression());}}        

2012/5/17 更新:

終於用模板解決了那個問題

#include <iostream>#include <string>#include <cstring>#include <cstdlib>#include <cstdio>using namespace std;#define STACK_INIT_SIZE 1024#define STACKINCREMENT 30char Precede_Matrix[7][7] = {{'>', '>', '<', '<', '<', '>', '>',},{'>', '>', '<', '<', '<', '>', '>',},{'>', '>', '>', '>', '<', '>', '>',},{'>', '>', '>', '>', '<', '>', '>',},{'<', '<', '<', '<', '<', '=', '0',},{'>', '>', '>', '>', '0', '>', '>',},{'<', '<', '<', '<', '<', '0', '=',}};char Precede ( char a, char b ){int i = 0;int j = 0;switch (a){case '+' : i = 0; break;case '-' : i = 1; break;case '*' : i = 2; break;case '/' : i = 3; break;case '(' : i = 4; break;case ')' : i = 5; break;case '#' : i = 6; break;default : cout << "Error1!" << endl;}switch (b){case '+' : j = 0; break;case '-' : j = 1; break;case '*' : j = 2; break;case '/' : j = 3; break;case '(' : j = 4; break;case ')' : j = 5; break;case '#' : j = 6; break;default : cout << "Error2!" << endl;}return ( Precede_Matrix[i][j] );}double Operate(double a, char oper, double b){switch (oper){case '+': return a + b;case '-': return a - b;case '*': return a * b;case '/': return a / b;default: cout << "Error3!" << endl; return -1;}}struct stack_char{char *base;char *top;int stacksize;};struct stack_double{double *base;double *top;int stacksize;};  // 計算結果可能是兩位元,只能用double,不能用char來存?template <class T2, class T1>void InitStack(T1 &S){S.base = (T2 *)malloc( STACK_INIT_SIZE * sizeof(T2) );if(!S.base)cout << "Overflow2!" << endl;S.top = S.base;S.stacksize = STACK_INIT_SIZE;  }template <class T1, class T2>void Push(T1 &S, T2 e){if(S.top - S.base >= S.stacksize)    // 判滿{S.base = (T2 *)realloc( S.base,(S.stacksize + STACKINCREMENT) * sizeof(T2) );if(!S.base)cout << "Overflow3!" << endl;S.top = S.base + S.stacksize;S.stacksize += STACKINCREMENT;}*S.top++ = e;}template <class T1, class T2>void Pop (T1 &S, T2 &e){if(S.top == S.base)                 // 判空cout << "Error5!" << endl;e = *--S.top;}template <class T2, class T1>T2 GetTop(T1 S){if (S.top == S.base)                // 判空cout << "Error6!" << endl;return *(S.top - 1);}bool IsOperand(char c){if( ('0' <= c && c <= '9') || c == '.' )//c是數字或小數點return true;elsereturn false;}int main(void){string str;while (cin >> str) {str.push_back('#');//  最後是#(結束標誌)double a;double b;char x;char theta;stack_char OPTR;InitStack<char> (OPTR);Push(OPTR, '#');stack_double OPND;InitStack<double> (OPND);int i = 0;char c = str[i++];double operand = 0;while ( !(c == '#' && GetTop<char> (OPTR) == '#') ){if ( IsOperand(c) )// c is operand{operand = atof( &str[i - 1] );//把從c開頭的數轉化成doublePush(OPND, operand);while( IsOperand(str[i]) )i++;c = str[i++];}else                            // c is operator or delimiter{switch (Precede (GetTop<char> (OPTR), c)){case '<':Push(OPTR, c);c = str[i++];break;case '=':Pop(OPTR, x);c = str[i++];break;case '>':Pop(OPTR, theta);Pop(OPND, b);Pop(OPND, a);Push(OPND, Operate(a, theta, b));break;default:cout << "Error8!" << endl;break;}}       }//  OPTR棧的棧頂元素和當前讀入的字元均為“#”//  即“#”=“#”時整個運算式求值完畢cout << GetTop<double> (OPND) << endl;free(OPTR.base);free(OPND.base);}return 0;}        

同時功能上改進了,歡迎體驗!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.