數據結構c語言實現表達式求值

表達式求值頭文件

#ifndef HEADEXP_H_INCLUDED

#define HEADEXP_H_INCLUDED


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define MAX 20


int GetNumFromStr( char str[] , int pos , float* num ) ;
int GetOperateFromStr( char str[] , int pos , char* opert ) ;
int IsOperate( char c ) ;
char PriorityOfOperation( char c1 , char c2 ) ;
float Calculate( float a , char theta , float b ) ;
float EvaluateExpression( char str[] ) ;
int InputExpression( char str[] ) ;

#endif // HEADEXP_H_INCLUDED


棧的頭文件

#ifndef HEAD_H_INCLUDED
#define HEAD_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define STACK_INIT_SIZE 10
#define STACK_INCR_SIZE 3


typedef char ElemType ;


typedef struct
{
    ElemType* sbase ;
    ElemType* stop ;
    int stacksize ;
} STACK ;


int InitStack( STACK* s ) ;
int DestroyStack( STACK* s ) ;
int IsEmpty( STACK* s ) ;
int ClearStack(STACK* s ) ;
int GetTop( STACK* s  , ElemType* e ) ;
int GetLength( STACK* s ) ;
int Push( STACK* s , ElemType e ) ;
int Pop( STACK* s , ElemType* e ) ;
int TraverseStack( STACK* s ) ;


#endif // HEAD_H_INCLUDED

主函數

#include "head.h"
#include "headexp.h"
int main()
{
    //char str[] = "-7+(-8*2*9)+28/4-7+1+3*10-7*8 =" ;
    //char str[] = "8*(5+9)=" ;
    float result = 0.0 ;
    char str[200] = "";
    /*float num ;
    char opr ;
    int position = 0 ;
    while( str[position] != '\0' )
    {
        if( IsOperate( str[position] ) )
        {
            position = GetOperateFromStr( str , position , &opr ) ;
            printf( "%c\n" , opr ) ;
        }
        else
        {
            position = GetNumFromStr( str , position , &num ) ;
            printf("%.2f\n" , num ) ;
        }
    }*/
    printf( "Please input the expression , end the expression with \" = \" , end the program with \"quit\" \n" ) ;
    while( 1 )
    {
        scanf( "%s" , str ) ;
        if( !strcmp( str , "quit" ) )
        {
            break ;
        }
        result = EvaluateExpression( str ) ;
        printf( "%s %.2f\n" , str , result ) ;
    }
    return 0 ;
}


 說明:這個課題全部原創,花費了不少心血,已經上傳到資源上。所有的函數在資源中均實現,並且可以包含括號和負號的計算表達式的加減乘除運算。如果感興趣,可以可以去下載我的資源,共同探討,順便給點積分,謝謝合作!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章