表達式求值


表達式求值考的挺多。

寫一份小結,

一般用 棧或者遞歸(遞歸棧) 來實現

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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM