zoukankan      html  css  js  c++  java
  • 前缀式求值 NYOJ128

    #include<iostream>
    #include<cstdlib>
    #include<stack>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    char c[1005];
    
    /*int Is(char c)
    {
    	if(c=='+' || c=='-' || c=='*' || c=='/')
    		return 1;
    	else
    		return 0;
    }
    
    float cal(float x1,char c,float x2)
    {
    	switch(c){
    	case'+':return x1+x2;break;
    	case'-':return x1-x2;break;
    	case'*':return x1*x2;break;
    	case'/':return x1/x2;break;
    	default: return 0;break;
    	}
    }
    
    float Eva(char c[],int n)
    {
    	stack<char> a;
    	a.push('#');
    	stack<float> b;
    	float f,pf;
    	int j;
    //	cout<<c<<endl;
    	int flag = 0;
    	for(int i=0; c[i] != '\0'; ++i)
    	{
    		if(c[i] == 32) ++i;
    		if(Is(c[i]))
    		{
    		//	cout<<c[i]<<endl;
    			a.push(c[i]);
    			flag = 0;
    		}
    		else
    		{
    			char num[30];
    			num[0] = '\0';
    			for(j=0; c[i] != 32 && c[i] != '\0'; j++)
    			{
    				num[j] = c[i];
    				++i;
    			}
    			if(c[i] == '\0')
    				--i;
    			num[j] = '\0';
    		//	cout<<num<<endl;
    			f = atof(num);
    			b.push(f);
    			if(flag)
    			{
    				b.pop();
    				pf = b.top();
    				b.pop();
    				b.push(cal(pf,a.top(),f));
    				a.pop();
    			}
    			pf = b.top();
    			flag = 1;
    		}
    	}
    	while(a.top() != '#')
    	{
    		pf = b.top();
    		b.pop();
    		f = b.top();
    		b.pop();
    		b.push(cal(pf,a.top(),f));
    		a.pop();
    	}
    	return b.top();
    }*/
    
    /*注释的是自己写的代码,提交就是不能AC可能是有没有考虑到的情况吧,下边的代码是参考别人的,递归用的非常好,也非常妙!还有就是又学习到了一个函数sscanf(c,"%s",ch);把字符数组里的字符复制到ch中,到空格为止!*/
    
    float Eva()
    {
    	char ch[20];
    	sscanf(c,"%s",ch);
    	int len = strlen(ch);
    	strcpy(c,c+len+1);
    	switch(ch[0])
    	{
    	case'+':return Eva()+Eva();
    	case'-':return Eva()-Eva();
    	case'*':return Eva()*Eva();
    	case'/':return Eva()/Eva();
    	default:return atof(ch);
    	}
    }
    
    int main()
    {
    //	freopen("in.txt","r",stdin);
    
    	while(gets(c))
    		printf("%.2f\n",Eva());
    	return 0;
    }
    

      

  • 相关阅读:
    Java 测试代码模板
    git 保存用户名和密码
    git 高级命令
    git 最常用命令
    git 冲突解决
    git diff命令
    nginx静态服务器的配置
    使用SFTP工具下载文件
    git log 格式化输出
    9-angular.fromJson
  • 原文地址:https://www.cnblogs.com/yaling/p/2985442.html
Copyright © 2011-2022 走看看