堆栈实现,计算后缀表达式

/*compute sufix expression*/
#include <stdio.h>
#include "stack.h"
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define TRUE	1
#define FASLE	0
double add( double op1, double op2 );
double sub( double op1, double op2 );
double mul( double op1, double op2 );
double div( double op1, double op2 );
static char operator_group[] = "+-*/";
static double (*op[4])( double , double ) = {
	add, sub, mul, div
};
int is_operator( char ch );
static char whitespace[] = " \t\f\v\n\r";
#define MAX_LEN		100
int main()
{
	double		cmp_temp1, cmp_temp2, cmp_result;
	double		ulti_result;
	char		*token;
	char		buffer[MAX_LEN];
	printf("Please input the expression\n");
	while( fgets( buffer, MAX_LEN, stdin ) != NULL ){		
	
		for( token = strtok( buffer, whitespace);
			token != NULL;
			token = strtok( NULL, whitespace ) ){
				if( is_operator( *token ) && *(token + 1) == '\0' ){
					cmp_temp2 = top();
					pop();
					cmp_temp1 = top();
					pop();
					switch( *token ){
					case '+':
						cmp_result = op[0]( cmp_temp1, cmp_temp2 );
						break;
					case '-':
						cmp_result = op[1]( cmp_temp1, cmp_temp2 );
						break;
					case '*':
						cmp_result = op[2]( cmp_temp1, cmp_temp2 );
						break;
					case '/':
						cmp_result = op[3]( cmp_temp1, cmp_temp2 );
						break;
					}
					push( cmp_result );
				}
				else {
					float		f_value;
					sscanf(token ,"%f", &f_value );
					push( f_value );
				}	
			}


	}
	/*打印结果*/
	ulti_result = top();
	pop();
	//堆栈应该为空;
	assert(is_empty())
	printf("the result of the expression is %f", ulti_result );
	return 0;

}

int is_operator(  char ch  )
{
	char	*ptr = &ch;
	if( strpbrk( ptr, operator_group ) == NULL )
		return FASLE;
	return TRUE;	
}

double add( double op1, double op2 )
{
	return op1 + op2;
}

double sub( double op1, double op2 )
{
	return op1 - op2;
}

double mul( double op1, double op2 )
{
	return op1 * op2;
}

double div( double op1, double op2 )
{
	if( op2 == 0 ){
		printf( "除数不能为0" );
		return FASLE;
	}
	return op1 / op2;
}

计算后缀表达式;

可以计算浮点数,负数,没有添加其他的运算符,只有+-*/

点赞