表达式求值

表达式求值考的挺多。

写一份小结,

一般用 栈或者递归(递归栈) 来实现

nyoj35-表达式求值

题目描述:
2
1.000+2/4=
((1+2)*5+1)/4=

样例输出:
1.50
4.00

这道题就是简单的 四则运算 带括号

用两个栈的做法

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include<iostream>
using namespace std;

/*nyoj35*/
/*
此题主要利用的是数据结构中栈的压入与弹出
把运算符和数据分别压入不同的栈中进行相应的操作
*/

stack<char> osta;//定义一个char类型的字符栈
stack<double> dsta;//定义一个double类型的数据栈


int main()
{
	int T;
	//scanf("%d", &T);
	cin >> T;
	while (T--)
	{
		char s[1010];
		//scanf("%s", &s[1]);//从下标1开始读入
		cin >> s+1;
		int len = strlen(&s[1]);
		s[0] = '(';
		s[len] = ')';//把读入的表达式左端用“(”括起来,右端的等号换成“)”
		for (int i = 0; i <= len; i++)
		{
			if (s[i] == '(')
				osta.push(s[i]);//是左括号则压入字符栈中
			else if (s[i] >= '0' && s[i] <= '9')
			{
				int b, K = 0;
				double v = 0;
				while (s[i] >= '0' && s[i] <= '9' || s[i] == '.')
				{
					if (s[i] == '.')//判断是否是小数点
					{
						b = i;//记录小数点的位置
						K = 1;//标记
					}
					else
						v = v * 10 + s[i] - '0';
					i++;
				}
				i--;
				if (K == 1)
					dsta.push(v / pow(10, i - b));
				else
					dsta.push(v);
			}
			else if (s[i] == '+' || s[i] == '-')
			{
				while (osta.top() != '(')//判断栈顶元素,同下
				{
					double a = dsta.top(); dsta.pop();
					double b = dsta.top(); dsta.pop();
					double c;
					switch (osta.top())
					{
					case '+':c = b + a; break;
					case '-':c = b - a; break;
					case '*':c = b * a; break;
					case '/':c = b / a; break;
					}
					dsta.push(c);
					osta.pop();
				}
				osta.push(s[i]);
			}
			else if (s[i] == '*' || s[i] == '/')
			{
				if (osta.top() == '*')
				{
					double a = dsta.top(); dsta.pop();
					double b = dsta.top(); dsta.pop();
					dsta.push(b * a);
					osta.pop();
				}
				else if (osta.top() == '/')
				{
					double a = dsta.top(); dsta.pop();
					double b = dsta.top(); dsta.pop();
					dsta.push(b / a);
					osta.pop();
				}
				osta.push(s[i]);
			}
			else if (s[i] == ')')
			{
				while (osta.top() != '(')
				{
					double a = dsta.top(); dsta.pop();
					double b = dsta.top(); dsta.pop();
					double c;
					switch (osta.top())
					{
					case '+':c = b + a; break;
					case '-':c = b - a; break;
					case '*':c = b * a; break;
					case '/':c = b / a; break;
					}
					dsta.push(c);
					osta.pop();
				}
				osta.pop();
			}
		}
		printf("%.2lf\n", dsta.top());
		dsta.pop();//弹出最后数据,以免影响下一次运算
	}
	return 0;
}

nyoj305-表达式求值

自定义运算符 add max min
用递归的做法:

https://blog.csdn.net/chang_mu/article/details/19483529

#include <stdio.h>
#include <string.h>
char str[301];
int start;
 
int max(int a, int b){
	return a > b ? a : b;
}
 
int min(int a, int b){
	return a < b ? a : b;
}
 
int val(){
	int v, n;
	switch(str[start]){
		case 'm': start += 4; 
			if(str[start - 2] == 'n') return min(val(), val());
			else return max(val(), val());
		case 'a': start += 4;
			return val() + val();
		case ',':
		case ')': ++start; return val();
		default: sscanf(str + start, "%d%n", &v, &n);
			start += n; return v;
	}
}
 
int main(){
	int t;
	scanf("%d", &t);
	while(t--){
		scanf("%s", str);
		start = 0;
		printf("%d\n", val());
	}
	return 0;
}

https://blog.csdn.net/duan_1998/article/details/78634116

#include<cmath>
#include<stack>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
int i;
char str[1000+10];

int dfs()
{
    int x=0,a,b;
    while(str[i]==','||str[i]==')')
        i++;
    if(str[i+1]=='d')
    {
        i+=4;
        return dfs()+dfs();
    }
    if(str[i+1]=='a')
    {
        i+=4;
        a=dfs();
        b=dfs();
        return a>b?a:b;
    }
    if(str[i+1]=='i')
    {
        i+=4;
        a=dfs();
        b=dfs();
        return a<b?a:b;
    }
    while(str[i]>='0'&&str[i]<='9')
        x=x*10+str[i++]-'0';
    return x;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        i=0;
        printf("%d\n",dfs());
    }
}

nyoj-1272-表达式求值

    • max运算

#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
stack<int> dsta;//数据栈 
stack<char> osta;//字符栈 
char s[1005];
int main()
{
    int T,i,j;
    scanf("%d",&T);
    while(T--)
    {
        scanf("\n%s",&s[1]);
        int len=strlen(&s[1]);
        s[0]='('; s[++len]=')';//在给定的表达式两端添加上一对括号 
        for(i=0;i<=len;i++)
        {
            if(s[i]=='(')
                osta.push(s[i]);
            else if(s[i]=='S')
            {
                osta.push('(');//压入一个左括弧 
                i+=3;
            }
            else if(s[i]>='0' && s[i]<='9')
            {
                int v=0;
                while(s[i]>='0' && s[i]<='9')
                    v=v*10+(s[i++]-'0');
                i--;
                dsta.push(v);
            }
            else if(s[i]=='+')
            {
                while(osta.top()!='(' && osta.top()!=',')
                {
                    int a=dsta.top(); dsta.pop();
                    int b=dsta.top(); dsta.pop();
                    int c;
                    switch(osta.top())
                    {
                        case '+':c=b+a;break;
                        case '*':c=b*a;break;
                    }
                    dsta.push(c);
                    osta.pop();
                }
                osta.push(s[i]);
            }
            else if(s[i]=='*')
            {
                if(osta.top()=='*')
                {
                    int a=dsta.top(); dsta.pop();
                    int b=dsta.top(); dsta.pop();
                    dsta.push(b*a);
                    osta.pop();
                }
                osta.push(s[i]);
            }
            else if(s[i]==')' || s[i]==',')//遇到逗号及时求值 
            { //当遇到 ','时,就把Smax的前半部分表达式的值求出来  
                
                //运算符号 都在这里计算 + - * / smax自定义 
                while(osta.top()!='(')
                {
                    int a=dsta.top(); dsta.pop();
                    int b=dsta.top(); dsta.pop();
                    int c,suma=0,sumb=0;
                    switch(osta.top())
                    {
                        case '+':c=b+a;break;
                        case '*':c=b*a;break;
                        case ',':{
                        //逐位分割求和 
                            while(b!=0)
                            {
                                sumb+=b%10; b/=10;
                            }
                            while(a!=0)
                            {
                                suma+=a%10; a/=10;
                            }
                            c=max(suma,sumb);
                            break;
                        }
                    }
                    dsta.push(c);
                    osta.pop();
                }
                osta.pop();
                if(s[i]==',')//求完值之后,把逗号压入栈内,以便后半部分Smax表达式的求值 
                    osta.push(s[i]);
            }
        }
        printf("%d\n",dsta.top());
        dsta.pop();
    }
    return 0;
}
posted @ 2019-05-01 22:15  fishers  阅读(1749)  评论(0编辑  收藏  举报