因为最后一个操作数没有弹出来,所以下次运算会被当成第一个操作数,如需要清空,输入'c‘即可
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXOP 100
#define NUMBER '0' //数字信号
void push(double d);
double pop(); //值栈
int getop(char *s); //获取输入字符
void printTop(); //打印值栈顶元素
int getCount(); //获取 值栈 个数
void swob(); //交换栈顶两个元素
void clear(); //清空值栈元素
int main() {
int type;
double op2;
char s[MAXOP];
while ((type= getop(s)) != EOF)
{
switch (type)
{
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '-':
//op2 = pop();
swob();
push(pop() - pop());
break;
case '*':
push(pop()*pop());
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error:除数不能为0\n");
break;
case '%':
op2 = pop();
if (op2 != 0.0) {
push((long int)pop() %(long int)op2); //%操作符,操作数不能是浮点数,所以强制转换成 long int类型了
}
else
printf("error:除数不能为0\n");
break;
case 'c': // 处理清空值栈函数
clear();
break;
case '\n':
printTop();
break;
default:
printf("error:unknown command\n");
break;
}
}
system("pause");
return 0;
}
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double d) {
if (sp < MAXVAL) {
val[sp++] = d;
}
else
{
printf("error:栈已满,不能存入%f\n", d);
}
}
double pop() {
if (sp > 0) {
return val[--sp];
}
else
{
printf("error:栈是空的\n");
return 0.0;
}
}
int getch(void);
void ungetch(int);
int dflag = 1; //一个数中是否‘.' ,没有则存入
int _flag = 1; // 用于判断'-' 是减号,还是负号
int getop(char *s) {
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
i = 0;
if (!isdigit(c)&& c!='.') {
if (c == 'c') { //如果是'c' 返回执行clear()
c = tolower(c); //全部转为小写
return c;
}
else if (c == '-'&& getCount()<2 && _flag) { //判断'-',如果val值栈里面有两个操作数
_flag = 0 ; //那么'-',当减号处理,_flag标示用于判断
} //一个操作数里面只能包含一个'-'符号
else
{
_flag = 1; //返回要把标示 复位
return c;
}
}
if (isdigit(c) || _flag == 0 || dflag == 0) {
while (1) {
if (isdigit(s[++i] = c = getch())) {
continue;
}
else if (c == '.' && dflag) {
if (i >= 1 && isdigit(s[i-1])) { //判断'.', 一个操作数里面只能包含一个.'符号
dflag = 0;
continue;
}
}
else
{
dflag = 1; //返回要把标示 复位
break;
}
}
}
s[i] = '\0';
if (c != EOF) {
ungetch(c);
}
_flag = 1;
dflag = 1;
return NUMBER;
}
void printTop()
{
if (sp > 0) {
printf("栈顶元素:%.8g\n", val[sp - 1]);
}
else
{
printf("元素为空,请继续输入:");
}
}
int getCount()
{
return sp;
}
void swob()
{
if (sp > 1) {
val[sp] = val[sp-1];
val[sp-1] = val[sp - 2];
val[sp - 2] = val[sp];
val[sp] = 0.0;
}
}
void clear()
{
while (sp > 0)
{
val[--sp] = 0.0;
}
}
#define BUFSIZE 100
char buf[BUFSIZ];
int bufp = 0;
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if (bufp >= BUFSIZE) {
printf("ungetch:字符缓冲已满\n");
}
else
{
buf[bufp++] = c;
}
}