COJ1183(计算表达式的值)

Description

 给出的表达式全为合法的四则运算表达式,含括号。

Input

 每行一个表达式,数字全为int型整数,长度不超过100字符

Output

 输出表达式的值,一律保留小数点后4位。

Sample Input

1
1+2
-1+2
-1+(-2)

Sample Output

1.0000
3.0000
1.0000
-3.0000
 
代码写得很混乱……
对于括号的处理,我用的是递归调用,对于运算符的优先级的处理,我是通过2遍扫描来完成的,第一遍计算乘除运算,第二遍计算加减运算。
View Code
#include <stdio.h>
#include <string.h>
#define N 101
struct node
{
    double ans;
    int k;
};
char s[N];
int n;
double NUM[N];
char OPT[N];
int top_num,top_opt;
double cal(int,int);
void DelSpace()
{
    int i;
    n=0;
    for(i=0;s[i];i++)
    {
        if(s[i]!=' ' && s[i]!='\t') s[n++]=s[i];
    }
    s[n]=0;
}
bool IsDigital(char c)
{
    if(c>='0' && c<='9')    return true;
    return false;
}
node FirstNum(int a,int b)
{
    node ret;
    int i;
    if(s[a]=='(')
    {
        int cnt=1;
        for(i=a+1;i<=b;i++)
        {
            if(s[i]=='(')   cnt++;
            if(s[i]==')')   cnt--;
            if(cnt==0)  break;
        }
        ret.ans=cal(a+1,i-1);
        ret.k=i+1;
        return ret;
    }
    if(IsDigital(s[a]))
    {
        char tmp[11];
        int k=0;
        for(i=a;i<=b && IsDigital(s[i]);i++)    tmp[k++]=s[i];
        tmp[k]=0;
        sscanf(tmp,"%lf",&ret.ans);
        ret.k=i;
        return ret;
    }
    if(s[a]=='+')   return FirstNum(a+1,b);
    if(s[a]=='-')
    {
        ret=FirstNum(a+1,b);
        ret.ans=-ret.ans;
        return ret;
    }
}
double cmpute(double a,double b,char c)
{
    switch(c)
    {
        case '+':   return a+b;
        case '-':   return a-b;
        case '*':   return a*b;
        case '/':   return a/b;
    }
}
double cal(int a,int b)
{
    double x;
    char c;
    double NUM[N];
    char OPT[N];
    int top_num=0,top_opt=0;
    node tmp;
    tmp=FirstNum(a,b);
    x=tmp.ans;
    NUM[top_num++]=x;
    while(tmp.k<=b)
    {
        c=s[tmp.k];
        tmp=FirstNum(tmp.k+1,b);
        if(c=='*' || c=='/')    NUM[top_num-1]=cmpute(NUM[top_num-1],tmp.ans,c);
        else    NUM[top_num++]=tmp.ans,OPT[top_opt++]=c;
    }
    for(int i=0;i<top_opt;i++)  NUM[0]=cmpute(NUM[0],NUM[i+1],OPT[i]);
    return NUM[0];
}
int main()
{
    while(gets(s))
    {
        DelSpace();
        double ans=cal(0,n-1);
        printf("%.4f\n",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/algorithms/p/2584689.html