Linux系统下用C语言实现浮点数四则运算表达式的求值
实现功能:
1. 支持任意长度四则运算表达式,允许的操作符是:"+","-","*","/","(",")",以“#”或“=”结束表达式的输入
2. 操作数是浮点数,可以小数形式或指数形式表示,如123.456和1.23456E2两种表示形式
3. C语言实现,在linux平台上运行,也可以在Cygwin上运行
4. 用命令行方式输入操作符和操作数
5.共两个文件:头文件和源代码文件
文件1: EvaluateExpression.c
-----------------------FILE: EvaluateExpression.c BEGIN--------------------------------------------------
/**
* File Name: EvaluateExpression.c
* Description: This file implements the function of the basic arithmetic calculations.
* All valid/acceptable operations are only addition,subtraction,multiplication,division.
* The valid operators are defined as {'+', '-', '*', '/', '(', ')', '#'}.
* The '#' sign is defined as the ending symbol of experession input.
* And it surpports the float oprand type only now.
*
* Author: Sean.Wang
* Contact Mail: Sean.Gn@gmail.com
* Completed Date: July 05, 2009
**/
#include "EvaluateExpression.h"
int main ( void )
{
float result = 0.0F;
printf ( "/nPlease enter an expression to evaluate,and ends with the pound sign:/n" );
result = ( float ) FloatEvaluateExpression();
printf ( "Its result:%f/n", result );
return 0;
}
/**
* Function Name: FloatEvaluateExpression(void)
* Description: Implementing the float operations of addition,subtraction,multiplication,division.
* Arguments: void
* Returns: float
**/
float FloatEvaluateExpression ( void )
{
STACK *sOPTR = ( STACK * ) malloc ( sizeof ( STACK ) ); /* sOPTR:Operator Stack*/
STACK *sOPND = ( STACK * ) malloc ( sizeof ( STACK ) ); /* sOPND:Operand Stack*/
char c = ' ';
char lastchar = ' ';
float a = 0.0F;
float b = 0.0F;
char theta = ' ';
float result = 0.0F;
float valf = 0.0F; /*the float value of the digital string input from STDIN*/
char strf[MAXLENGTH] = {'/0'}; /*the valid float string input from STDIN*/
int idx = 0;
bool pointAvail = TRUE; /*Decimal Point available*/
bool expAvail = TRUE; /*Exponent available*/
InitStack ( sOPTR );
Push ( sOPTR, '#' );
lastchar = '#';
InitStack ( sOPND );
c = getchar();
while ( c != '#' || ( ( char ) GetTop ( sOPTR ) ) != '#' )
{
while ( isspace ( c ) )
c = getchar();
if ( c == '=' )
c = '#';
idx = 0;
if ( ( c == '-' || c == '+' ) && ( IsOprator ( lastchar ) ) )
{
strf[idx++] = c;
c = getchar();
if ( ! ( isdigit ( c ) || c == '.' ) )
{
printf ( "EXIT_FAILURE: format is invalid or undefined,!/n" );
exit ( EXIT_FAILURE );
}
}
strf[idx] = '/0';
if ( isdigit ( c ) || c == '.' )
{
lastchar = '0';
pointAvail = TRUE; /*Decimal Point available*/
expAvail = TRUE; /*Exponent available*/
do
{
if ( c == '.' )
{