多项式运算(渣算法)

来源:互联网 发布:金耳朵英语软件 编辑:程序博客网 时间:2024/05/17 00:55
#include <cstdio>#include <string>#include <string.h>int num[100];int pointnum=-1;void push(int);int popn(bool);bool isNullnum();int chr[100];int pointchr=-1;void push(char);char popc(bool);bool isNullchr();char str[256];void algo();int main(){    bool HaveNum=false;    memset(str,0,sizeof(str));    scanf("%s",str);    str[strlen(str)]=')';    push('(');    int temp=0;    for(int i=0;i<strlen(str);i++)    {        if(str[i]>='0' && str[i]<='9')        {            HaveNum=true;            temp*=10;            temp+=str[i]-48;        }        else        {            char chr=str[i];            if(HaveNum==true)            {                push(temp);                HaveNum=false;                temp=0;            }            switch(chr)            {            case '+':                while(popc(false)!='(' && !isNullchr()) algo();                push(chr);                break;            case '-':                while(popc(false)!='(' && !isNullchr()) algo();                push(chr);                break;            case '*':                while(popc(false)!='(' && popc(false)!='+' && popc(false)!='-' && !isNullchr()) algo();                push(chr);                break;            case '/':                while(popc(false)!='(' && popc(false)!='+' && popc(false)!='-' && !isNullchr()) algo();                push(chr);                break;            case '(':                push(chr);                break;            case ')':                while(popc(false)!='(')                {                    algo();                }                if(popc(false)=='(')                    chr=popc(true);                break;            }        }    }    while(!isNullchr())    {        algo();    }    printf("%d\n",popn(false));    return 0;}void push(int i){    num[++pointnum]=i;}void push(char i){    chr[++pointchr]=i;}int popn(bool i){    if(i==true)        return num[pointnum--];    else        return num[pointnum];}char popc(bool i){    if(i==true)        return chr[pointchr--];    else        return chr[pointchr];}bool isNullchr(){    if(pointchr!=-1)        return false;    else        return true;}bool isNullnum(){    if(pointnum!=-1)        return false;    else        return true;}void algo(){    int b=popn(true);    int a=popn(true);    char chr=popc(true);    switch(chr)    {    case '+':        push(a+b);        break;    case '-':        push(a-b);        break;    case'*':        push(a*b);        break;    case '/':        push(a/b);        break;    }}