逆波兰计算器(后缀计算器)
第一版本。输入函数是个坑。
先就这样了,以后想到了再来改进输入函数。
有一点小BUG,如果最后的运算符是减号,必须手动加一个空格或者多按一下回车。
这是为了可以进行负数计算。
看来还得继续努力修正这个问题。
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef double OpType;
void
MakeStack( void );
void
DeleteStack( void );
void
Push( OpType value );
OpType
Top( void );
int
IsEmpty( void );
int
IsFull( void );
int
GetOperand( void );
int
main( void )
{
int ch;
OpType op;
MakeStack();
while( EOF != ( ch = GetOperand() ) )
{
switch( ch )
{
case '+':
Push( Top() + Top() );
break;
case '-':
op = Top();
Push( Top() - op );
break;
case '*':
Push( Top() * Top() );
break;
case '/':
op = Top();
Push( Top() / op );
break;
case '%':
op = Top();
Push( ( OpType )( ( int )Top() % ( int )op ) );
break;
case '\n':
if( IsEmpty() )
break;
printf( "%.2lf\n", Top() );
DeleteStack();
MakeStack();
break;
default:
break;
}
}
printf( "Bye.\n" );
DeleteStack();
return 0;
}
#define MAXSIZE 128
#include <ctype.h>
int
GetOperand( void )
{
int ch;
int lx;
char Temp[ MAXSIZE ];
for( lx = 0; MAXSIZE - 1 > lx && EOF != ( ch = getchar() ); ++lx )
{
if( isdigit( ch ) || '.' == ch )
{
if( 0 == lx )
Temp[ lx++ ] = '0';
Temp[ lx ] = ch;
}
else if( '-' == ch )
{
if( 0 == lx )
Temp[ lx ] = ch;
else
break;
}
else
break;
}
Temp[ lx ] = '\0';
if( 1 == strlen( Temp ) && '-' == Temp[ 0 ] )
return Temp[ 0 ];
if( 0 < lx )
Push( atof( Temp ) );
return ch;
}
#define INITSIZE 128
static OpType *Stack;
static int stacktop = -1;
static int CurrentSize = INITSIZE;
void
MakeStack( void )
{
Stack = ( OpType * )malloc( CurrentSize * sizeof( OpType ) );
assert( NULL != Stack );
}
void
DeleteStack( void )
{
free( Stack );
Stack = NULL;
CurrentSize = INITSIZE;
stacktop = -1;
}
void
Push( OpType value )
{
assert( !IsFull() );
Stack[ ++stacktop ] = value;
}
OpType
Top( void )
{
assert( !IsEmpty() );
return Stack[ stacktop-- ];
}
int
IsEmpty( void )
{
return -1 == stacktop;
}
int
IsFull( void )
{
OpType *Temp;
if( stacktop == CurrentSize - 1 )
{
CurrentSize += INITSIZE;
Temp = ( OpType * )realloc( Stack, CurrentSize * sizeof( OpType ) );
if( NULL == Temp )
{
CurrentSize -= INITSIZE;
return 1;
}
Stack = Temp;
return 0;
}
else
return 0;
}
[此贴子已经被作者于2017-4-7 20:58编辑过]









自学了很久进展不大~就是差个删除节点还要弄懂~

~~~~
~~~我还是要去百度一下什么是逆波兰计算~