poj百练 2694

原题:

逆波兰表达式求值;

一开始想是将符号放入栈中,将数字型字符串取出存入double型数组,然后进行求值,代码如下:

#include<stdio.h>

#include<ctype.h>

#include<string.h>

#include<math.h>

typedef struct stacknode

{

char stack[100];

int top;

}Stack

;

double cal(char op,double a,double b)

{

switch(op)

{

case '*':return a*b;break;

case '/':return b/a

break;case '-':return b-a;break;

case '+':return a+b;break;}}

int main(){

Stack s;s.top=-1;char s1[100];

double s2[100];

int i,j=0,k=0;  

   double data=0;  

  gets(s1);

for(i=0;i<=strlen(s1);i++)

{

if(isdigit(s1[i]))

{data=(data)*10+s1[i]-'0';

}

else if(s1[i]=='.'){

while(isdigit(s1[i++])

){k++;data=data+(s1[i]-'0')*pow(10,-k);}}

else if(s1[i]==' '&&(data!=0||s1[i-1]=='0')||s1[i]=='\0')

{

         s2[j++]=data;     

    data=0;}elsedata=0;}

for(i=0;i<j/2;i++){data=s2[i];s2[i]=s2[j-i-1];s2[j-i-1]=data;

}

for(i=0;i<strlen(s1);i++)

{

if(isdigit(s1[i])==0&&s1[i]!=' '&&s1[i]!='.')

{          s.stack[++s.top]=s1[i];}}i=0;while(s.top!=-1)

{      double a=s2[i++];     double b=s2[i++];      s2[j++]=cal(s.stack[s.top--],a,b);

}

printf("%f\n",s2[--j]);return 0;

}

提交后,我的代码比起其他提交者的长了近3倍,而且它显示aw,可是运行和结果都正确(在我机器),一度让我纠结。

然后看了下面的提示。查了一下atof函数。然后用递归写了个代码

#include<stdio.h>

#include<stdlib.h>

double cal(){

char a[10];scanf("%s",a);

switch(a[0])

{

case '*':return cal()*cal();

case '/':return cal()/cal();

case '+':return cal()+cal();

case '-':return cal()-cal();

default:return atof(a);

}

}

main()

{ 

printf("%f\n",cal());

}

值得注意的是:return,之后就不向下执行,就不需要break;多了反而报错。

每个输入一个字符串(数字要么符号),遇符号执行switch然后将执行case,压栈,这么做其实就是将符号和数字分别压栈,然后计算。

其复杂度和上边的长代码一至。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值