首页 新闻 会员 周边

把它改成适用于全体实数并且可以运算带()的计算器,例如:3*(4+5)的形式

0
悬赏园豆:100 [已关闭问题] 关闭于 2014-09-11 09:24

#include <stdio.h>

#define smax 10
#define emax 255

int power(int x,int y)
{
 int t,s=1;
 for (t=0; t<x;t++)
  s=s*y;
 return s;
}

int calc(char op, int x, int y)
{
 int num;
 if (op=='+')
  num=x+y;
 else if (op=='-')
  num=y-x;
 else if (op=='*')
  num=y*x;
 else if (op=='/')
  num=y/x;
 else if (op=='^')
  num=power(x,y);
 return num;
}
int rank(char op)
{
 int r;
 if (op=='+') r=0;
 else if (op=='-') r=1;
 else if (op=='*') r=2;
 else if (op=='/') r=2;
 else if (op=='^') r=3;
 return r;
}
void main()
{
 //栈
 int s[smax];
 char op[smax];
 int top=0;
 int otop=0;
 //其他变量
 int i,num,x,y;
 int ans=0;
 int rtop,rinput;
 char o;
 //表达式存储
 char ex[emax];
 
 //实现计算器的功能
 //输入表达式
 scanf("%s", ex);
 i=0;
 num=0;
 //读出每个字符
 s[0]=0;
 top=1;
 op[0]='+';
 otop=1;
 while (1)
 {
  //分解每个数和符号
  if (ex[i] >=48 && ex[i]<58)
  {
   //读到数字
   num=num*10+ex[i]-48;
  }
  else
  {
   //前一个数字已经输入完毕
   //数字入栈
   s[top]=num;
   top=top+1;
   num=0;
   if (ex[i]==0)
    break;
   else
   {
    //判断符号优先级
    //如果优先级低于当前栈顶的符号的优先级,计算栈顶符号对应的运算
    rinput=rank(ex[i]);
    //符号栈顶元素出栈
    otop=otop-1;
    o=op[otop];
    rtop=rank(o);
    
    while (rtop>=rinput && rtop!=0)
    {

     //计算
     //数字出战
     top=top-1;
     x=s[top];
     top=top-1;
     y=s[top];
     s[top]=calc(o,x,y);
     top=top+1;
     //读出下一个栈顶符号
     otop=otop-1;
     o=op[otop];
     if (o=='+')
      rtop=0;
     else
      if (o=='-') rtop=1; 
    }
    //原先的放回
    op[otop]=o;
    otop=otop+1;
    //新的符号入栈
    op[otop]=ex[i];
    otop=otop+1;
   }
  }
  i=i+1;
 }
 while (otop!=0)
 {
  //数字出战
  top=top-1;
  x=s[top];
  top=top-1;
  y=s[top];
 
  //符号出栈
  otop=otop-1;
  o=op[otop];
  s[top]=calc(o,x,y);
  top=top+1;
 }
 ans= s[0];
 //输出结果
 printf("%s=%d\n",ex,ans);
}

夜雨星辰-的主页 夜雨星辰- | 初学一级 | 园豆:194
提问于:2013-07-06 21:02
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册