C 언어 - 접미사 표현 식 값 구하 기

20501 단어 데이터 구조
주: 가장 주의해 야 할 것 은 코드 에 표 시 된 getchar () 함수 의 사용 입 니 다.
#include
#include
#include

#define False 0
#define True 1

typedef struct
{
	int top;
	int maxSize;
	double *element;
}Stack;

//   
void Create(Stack *S,int mSize)
{
	S->maxSize = mSize;
	S->element = (double*)malloc(sizeof(double)*mSize);
	S->top = -1;
}

//   
void Destroy(Stack *S)
{
	S->maxSize = -1;
	free(S->element);
	S->top = -1;
}

//    
int IsEmpty(Stack *S)
{
	return S->top == -1;
}

//    
int IsFull(Stack *S)
{
	return S->top == S->maxSize;
}

//       
int Top(Stack *S,double *x)
{
	if(IsEmpty(S))
		return False;
	*x = S->element[S->top];
	return True;
}

//          
int Push(Stack *S,double x)
{
	if(IsFull(S))
		return False;
	S->top++;
	S->element[S->top] = x;
	return True;
}

//       
int Pop(Stack *S)
{
	if(IsEmpty(S))
		return False;
	S->top--;
	return True;
}

void Clear(Stack *S)
{
	S->top = -1;
}


int GetOperands(Stack *S,double *op1,double *op2)
{
	if(!Top(S,op1))
	{
		printf("Missing Operand!");
		return False;
	}
		
	Pop(S);
	if(!Top(S,op2))
	{
		printf("Missing Operand!");
		return False;
	}
	Pop(S);
	
	return True;
	
}

void DoOperator(Stack *S,char ope)
{
	int result;
	double ope1,ope2;
	result = GetOperands(S,&ope1,&ope2);
	if(!result)
		Clear(S);
	else
	{
		switch(ope)
		{
			case '+':
				Push(S,ope2+ope1);
				break;
			case '-':
				Push(S,ope2-ope1);
				break;
			case '*':
				Push(S,ope1*ope2);
				break;
			case '/':
				if(fabs(ope2)<1e-6)
				{
					printf("Divided by 0!");
					Clear(S);
				}
				else
				{
					Push(S,ope2/ope1);
				}
			    break;
			case '^':
				Push(S,pow(ope1,ope2));
				break;
			
		}
		
	}
}

int main()
{
	Stack S;
	Create(&S,10);
	char c;
	double newop;
	scanf("%c",&c);
	for(;c!='#';)
	{
		switch(c)
		{
			case '+':			
			case '-':				
			case '*':
			case '/':				
			case '^':
				DoOperator(&S,c);
				break;
			default:
				newop = c-'0';
				Push(&S,newop); 		
		}
//       getchar   !!! 
//            ! 
		getchar();
		scanf("%c",&c);
	}
	if(Top(&S,&newop))
		printf("%f",newop);
	
	Destroy(&S);
	return 0;
}

좋은 웹페이지 즐겨찾기