上次所写的逆波兰计算器完全就是在云里雾里的情况下抄袭而成,这次经过多次的调试和自己动手写,明白了逆波兰运算器的原理,当然,例如TCPL书中所写的ungetch我是没有用到的。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
/**
* 创建人: C coder
* 创建日期:2019-3-13
* 该程序为逆波兰计算器,主要用于初步了解
* 信息在内存中的存储方式
*
**/
#define MVAL 100
#define NUMBER '0' //代表传回的是数字
double Atof(char *pstr);
double pop();
void push();
int getop(char *cNumber);
int main()
{
char cNumber[MVAL];
int nPos = 0;
char type;
while( (type = getop(cNumber)) != EOF )
{
switch(type)
{
case NUMBER:
{
push(Atof(cNumber));
break;
}
case '+':
{
push(pop() + pop());
break;
}
case '*':
{
push(pop() * pop());
break;
}
case '-':
{
double nTmp = pop();
push(pop() - nTmp);
break;
}
case '/':
{
double nTmp = pop();
push(pop() / pop());
break;
}
case '\n':
{
printf("%lf", pop());
break;
}
default:
{
printf("this is not a number or operator!");
break;
}
}
}
return 0;
}
double Atof(char *pstr)
{
int i = 0;
int j = 0;
double dNumber = 0;
int sign = 0;
double power = 1;
for(; isspace(pstr[i]);i++);
sign = (pstr[i] == '-') ? -1 : 1; //判断正负
if(pstr[i] == '-' || pstr[i] == '+')
{
i++;
}
for(; pstr[i] != '.' && pstr[i] != '\0'; i++)
{
dNumber = (pstr[i] - '0') + dNumber * 10;
}
if(pstr[i] == '.')
{
i++;
}
else
{
return sign * dNumber;
}
for(; pstr[i] != '\0'; i++)
{
dNumber = (pstr[i] - '0') + dNumber * 10;
power *= 10;
}
dNumber = dNumber / power;
return sign * dNumber;
}
#define MAXVAL 100
double val[MAXVAL]; //用于保存数字
int valpos = 0; //用于保存val的深度
void push(double number)
{
if(valpos >= 100)
{
printf("the val can't push!");
}
else
{
val[valpos++] = number;
}
}
double pop()
{
if(valpos <= 0)
{
printf("the val haven't any number");
}
else
{
return val[--valpos];
}
}
/**下面函数用于实现getop功能**/
char getch();
void ungetch(char c);
int getop(char *cNumber)
{
int nPos = 0; //用于
char c = '0';
while( (cNumber[0] = c = getch()) == ' ' || c == '\t' );
if( !isdigit(c))
return c;
if(isdigit(c))
{
while(isdigit(cNumber[++nPos] = c = getch( )));
}
if(cNumber[nPos] == '.')
{
while(isdigit(cNumber[++nPos] = c = getch()));
}
cNumber[nPos] = '\0';
return NUMBER;
}
#define MAXBUFSIZE 100
int strpos = 0;
char str[MAXBUFSIZE]; //用于存放字符
char getch()
{
if(strpos <= 0)
{
return getchar();
}
else
{
return str[--strpos];
}
}
void ungetch(char c)
{
if(strpos >= 100)
{
printf("the strpos is full!");
}
else
{
str[strpos++] = c;
}
}