南阳 oj 表达式求值 题目35 数据结构 NYO题目链接

给大家推荐个靠谱的公众号程序员探索之路,大家一起加油 

建议不会的看别人的代码自己在之上模拟一遍,只要耐心模拟就会做出来

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=35
 

#include<stdio.h>
 #include<string.h>
 #include<stdlib.h>
 #define N 1000
 using namespace std;
 char s[N];//存储字符串 
char str1[N];//存储'o'-到'9'的字符 
char str2[N];//存储运算符 
int top1,top2;//利用数组模拟栈 
int compare(char x)//优先级比较 
{
  switch(x)
  {
   case '+' :
   case '-' :return 1;
   case '*' :
   case '/' :return 2;
   case '(' :return 0;
   default: return -1; 
  }
 }
 void zhuan()//转换 
{
  int k;
  top1=-1,top2=-1;//初始化头 
 scanf("%s",s);
  k=strlen(s);
  for(int i=0;i<k;i++)
  {
   if(s[i]>='0'&&s[i]<='9'||s[i]=='.')//如果是数字进去str1数组中 
  {
    top1++;
    str1[top1]=s[i];
      }
   else if(s[i]=='(')//如果是'('进入str2中 
  {
    top2++;
    str2[top2]=s[i];
      }
   else if(s[i]==')')//如果是')'说明str2中有运算符 
  {
    while(str2[top2]!='(')
    {
     top1++;
     str1[top1]=' ';
     top1++;
     str1[top1]=str2[top2];
     top2--;
    }
    top2--;//把'('出去 
  }
      else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')//如果是运算符比较优先级 
  {
     top1++;
     str1[top1]=' ';
     while(compare(s[i])<=compare(str2[top2]))//如果s[i]优先级低于之前也就是str2中的运算符  把str2中的运算符给str1 
     {
      top1++;
    str1[top1]=str2[top2];
    top1++;
    str1[top1]=' ';
    top2--;
     }
     top2++;
     str2[top2]=s[i];//如果str2高进入str2 
      }
  }
  while(top2!=-1)//将剩余的进入str1中 
 {
   top1++;
   str1[top1]=' ';
   top1++;
   str1[top1]=str2[top2];
   top2--;
  }
  top1++;
  str1[top1]=' ';
  top1++;
  str1[top1]='=';
  top1++;
  str1[top1]='\0';
 } 
 void sum()//计算 
{
  double a1,a2,d[N];
  char ch;
  char s1[100],st[N];
  int k,t=-1;
  for(int i=0;i<top1;i++)
  {
   k=0;
   ch=str1[i];
   while(str1[i]!=' ')
   {
    if(str1[i]=='=') break;
    s1[k++]=str1[i];
    i++;
   }
   if(ch>='0'&&ch<='9')
   {
    s1[k]='\0';
    t++;
    d[t]=atof(s1);
   }
   else
   {
    switch(ch)
    {
     case '+' :
      a2=d[t];
      t--;
      a1=d[t];
      t--;
      t++;
      d[t]=a1+a2;
      break;
     case '-' :
      a2=d[t];
      t--;
      a1=d[t];
      t--;
      t++;
      d[t]=a1-a2;
      break;
     case '*' :
      a2=d[t];
      t--;
      a1=d[t];
      t--;
      t++;
      d[t]=a1*a2;
      break;
     case '/' :
      a2=d[t];
      t--;
      a1=d[t];
      t--;
      t++;
      d[t]=a1/a2;
      break;
     default : break;
    }
   }
  }
  printf("%.2lf\n",d[t]);
 }
 main()
 {
  int n;
  scanf("%d",&n); 
  while(n--)
  {
   zhuan();
   sum(); 
  } 
 } 


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值