小白写逆波兰计算器

编程入门 行业动态 更新时间:2024-10-07 22:22:53

小白写逆<a href=https://www.elefans.com/category/jswz/34/1748907.html style=波兰计算器"/>

小白写逆波兰计算器

/*逆波兰计算器:淮南师范学院 电子工程学院 夏健钧 2017/3/24*/
/*逆波兰计数法:参考维基百科*/
#include<stdio.h>
#include<stdlib.h>  /*为了使用atof()函数*/
#include<ctype.h>
#define MAXOP 100   /*操作数或运算符的最大长度*/
#define NUMBER '0'  /*标识找到一个数*/

int getop (char [] );
void push (double);
double pop (void);

/* 逆波兰计算器 */
int main(int argc, const char *argv[])
{
 int type;
 double op2;
 char s[MAXOP];


 while ((type = getop(s)) != EOF)
 {
  switch (type)
  {
   case NUMBER:
     push(atof(s)); /*atof(s):将字符串(s)转换为双精度的浮点数据*/
     break;
   case '+':
       push(pop() + pop()); /*先弹出并返回栈顶的值,将两值相加后,压到栈底*/
       break; 
   case '*':
       push(pop() * pop()); /*先弹出并返回栈顶的值,将两值相乘后,压到栈底*/
       break; 
   case '-':            /* 因 * / 不满足交换律 需要考虑弹出的次序*/
       op2 = pop ();  /*将先输入的值赋值给op2,后输入的值减去op2,将结果压入栈底*/
       push(pop() - op2);
       break;

   case '/':
       op2 = pop ();  /* 将先输入的值赋值给op2,后输入的值除以op2,将结果压入栈底 */
       if (op2 != 0.0) /* 0 做分子无意义 */
        push(pop() / op2);
       else
        printf("error: zero divisor\n");
       break;
   case '\n':
       printf("\t%.8g\n", pop()); /*当按下 enter 键后 输出栈顶的值,即最终的计算结果*/
       break;
   default:
       printf("error: unknown command %s\n",s);
       break;
     } 
 
 }
 return 0;
}

#define MAXVAL 100  /* 栈VAL的最大深度 */

int sp = 0;     /* 下一个空闲栈的位置 */
double val[MAXVAL]; /* 值栈 */

/* push函数: 把f压入到值栈中 */
void push (double f)
{
 if (sp < MAXVAL)
  val [sp++] = f;
 else
  printf("error: stack full,can't push %g\n",f);

}

/* pop函数: 弹出并返回栈顶的值 */
double pop (void)
{
 if (sp > 0)
  return val [--sp];
 else
 {
  printf("error: stack empty\n");
  return 0.0;
 
 }

}

int getch(void);
void ungetch(int);
/* getop函数:获取下一个运算符或数值操作符 */
int getop (char s[])
{
 int i, c;
 while ((s[0] = c = getch()) ==  ' ' || c == '\t') /* 跳过空格与制表符 */
  ;
  s[1] = '\0';
 if (!isdigit(c) && c != '.') /*isdigit(c):测试字符是否为数字:是,返回非0,不是返回0*/
  return c;         /* 不是数 */
 
  i = 0;
 if (isdigit(c))       /*收集整数部分 */
  while (isdigit(s[++i] = c = getch()))
   ;
 if (c == '.')      /* 收集小数部分 */
  while (isdigit(s[++i] = c = getch()))
   ;
  s[i] = '\0';
 if (c != EOF)
   ungetch(c);  /* 把字符压回输入中 */
  return NUMBER;

#define BUFSIZE  100
char buf [BUFSIZE]; /* 用于ungetch函数的缓冲区*/
int bufp = 0 ;  /* buf中下一个空闲位置 */
int getch (void)   /*取一个字符(可能是压回的字符) */
{
 return (bufp > 0) ? buf [--bufp] : getchar();
 
}

void ungetch( int c )  /* 把字符压回到输入中 */
{
 if (bufp >= BUFSIZE )
  printf("ungetch: too many characters\n");
 else
  buf[bufp++] = c;

}

 

 

 

更多推荐

小白写逆波兰计算器

本文发布于:2024-02-06 12:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1748851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:波兰   计算器   小白写逆

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!