02-3

哈哈哈哈哈~竟然一次过!!!

不过样例确实给了很多提示

参考了别人代码

http://www.patest.cn/contests/mooc-ds/02-3

/*
  title:02-3
  问题分类:
  新思路:
  1.倒着看,遇到数字进栈,运算符出操作数2个
  2.对于数字,就当做无小数点,直到遇到小数点,除以该权值,重置权值,再算
  3.数字正负问题 
*/
#include<stdio.h>
#include<string.h>
double ss[40];
int top=-1;
void push(double x){
	ss[++top]=x;
}
bool flag;//除数为0 
double pop(){
	if(top!=-1){
		return ss[top--];
	}else{
		flag=1;
	}
	
}

double com(char c){
	double a=pop();
	double b=pop();
	if(c=='+'){
		return (a+b);
	}else if(c=='-'){
		return (a-b);
	}else if(c=='*'){
		return (a*b);
	}else if(c=='/'){
		if(b==0){
			//printf("ERROR\n");
			flag=1;
		}else{
			return (a/b);
		}
	}

}
int main(){
	freopen("in.txt","r",stdin);
    char s[40];
    while(gets(s)){
		int len=strlen(s);
		//输入有空行 
		if(len==0){
			continue;
		}
		for(int i=len-1;i>=0;){
			if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
				double c=com(s[i]);
				if(flag==1){
					printf("ERROR\n");
					break;
				}
				push(c);
				i--;
			}else if(s[i]==' '){
				i--;
			}else{
				double quan=1;
				double x=0;
				while(s[i]!=' '&&i>=0){
					if(s[i]=='.'){
						x/=quan;
						quan=1;
					}else if(s[i]=='+'||s[i]=='-'){
						if(s[i]=='-'){
							x=0-x;
						}	
					}
					else{
						x+=(quan*(s[i]-'0'));
						quan*=10;
					}
					i--; 
				}
				push(x);
				x=0;
				quan=1;
				
			}
		}
		if(!flag){
			double res=0;
			int count=0;
			while(top!=-1){
				res=pop();
				count++;
			}
			if(count!=1){
				printf("ERROR\n");
			}else{
				printf("%.1lf\n",res);
			}
			
		}
		
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值