南阳oj 郁闷的c小加(二) 题目267

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

#include<stdio.h>
#include<stack>
#include<string.h>
#define N 1000
#include<stdlib.h>
using namespace std;
stack<char> str;//字符栈  转化为后缀式
stack<double> num;//数字栈  计算值
char s1[N],s2[N],s3[1000000];
int top;
int com(char x)//比较优先级
{
 switch(x)
 {
  case '+':
  case '-':return 1;
  case '*':
  case '/':return 2;
  default:return -1;
    }
}
void zhuan()//转化后缀式
{
 scanf("%s",s1);//输入字符串
 int k=strlen(s1);//获取长度
 top=-1;//初始化头
 str.push('#');//进入一个字符以防访问过界
 for(int i=0;i<k;i++)
 {
  if(s1[i]>='0'&&s1[i]<='9'||s1[i]=='.')//数字就进入
  {
   top++;
   s2[top]=s1[i];
  }
  else if(s1[i]=='+'||s1[i]=='-'||s1[i]=='*'||s1[i]=='/')
  {
   top++;
   s2[top]=' ';
   if(com(s1[i])>com(str.top())) str.push(s1[i]);//比较优先级,如果大就进入栈
   else//否则就输出
   {
    while(com(str.top())>=com(s1[i]))
    {
   top++;
     s2[top]=str.top();
     top++;
     s2[top]=' ';
  str.pop();
    }
   str.push(s1[i]);
   }
   }
 else if(s1[i]=='(') str.push(s1[i]);
 else if(s1[i]==')')
 {
  while(str.top()!='(')
  {
   top++;
   s2[top]=' ';
   top++;
   s2[top]=str.top();
   str.pop();
  }
  str.pop();//删除左括号
  }
   }
   while(str.top()!='#')//将剩余的全部输出
   {
    top++;
    s2[top]=' ';
  top++;
 s2[top]=str.top();
 str.pop();
   }
   for(int i=0;i<=top;i++)
   {
    if(s2[i]!=' ') printf("%c",s2[i]);
   }
   printf("=\n");
}
void ji()
{
  while(!num.empty())
   num.pop();
  double a1,a2;
  char x;
  int k,t=-1;
  for(int i=0;i<=top;i++)
  {
   k=0;
   x=s2[i];
   while(s1[i]!=' ')
   {
    if(s2[i]==' ') break;
    s3[k]=s2[i];
    k++;
    i++;
   }
   if(x>='0'&&x<='9')
   {
    s3[k]='\0';
    t++;
    num.push(atof(s3));
   }
   else
   {
    switch(x)
    {
     case '+':
      a1=num.top();
      num.pop();
      a2=num.top();
      num.pop();
      num.push(a1+a2);
      break;
     case '-':
      a1=num.top();
      num.pop();
      a2=num.top();
      num.pop();
      num.push(a2-a1);
      break;
     case '*':
      a1=num.top();
      num.pop();
      a2=num.top();
      num.pop();
      num.push(a2*a1);
      break;
     case '/':
      a1=num.top();
      num.pop();
      a2=num.top();
      num.pop();
      num.push(a2/a1);
      break;
    }
   }
  }
  printf("%.2lf\n\n",num.top());
}
int main()
{
 int t;
 scanf("%d",&t);
 while(t--)
 {
     zhuan();
     ji();
 }
 return 0;
}
 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值