Pagini recente » Cod sursa (job #545275) | Cod sursa (job #617479) | Cod sursa (job #2972538) | Cod sursa (job #1558395) | Cod sursa (job #1085954)
#include <stdio.h>
#include <stdlib.h>
#define _FULL_STACK 50
#define _EMPTY_STACK -1
struct stack{
int top;
int elements[_FULL_STACK];
};
void empty_stack(stack *s);
int isempty(stack *s);
int push(stack *s, int e);
int pop(stack *s);
int isoperator(char c);
int isdigit(char c);
int priotity(char o);
void inix2postfix(char *inix, char *postfix);
int evaluate(char *pexp);
int main(){
char text[100] = { '\0'}, postfix[100] = {'\0'};
FILE *in = fopen("evaluare.in", "r");
FILE *out = fopen("evaluare.out", "w");
fgets(text, 100, in);
inix2postfix(text, postfix);
fprintf(out, "%d", evaluate(postfix));
return 0;
}
void inix2postfix(char *inix, char *postfix){
char *i, *p;
char n;
stack s;
empty_stack(&s);
i = &inix[0];
p = &postfix[0];
while(*i != '\0'){
while(*i == ' ' || *i == '\t')
i++; /* ignore spaces */
if(isdigit(*i)){
while(isdigit(*i)){
*p = *i;
i++;
p++;
}
*p = ' ';p++;
}
if(*i == '('){
push(&s, *i);
}
if(*i == ')'){
n = pop(&s);
while(n != '('){
*p = n;
p++;
*p = ' ';
p++;
n = pop(&s);
}
}
if(isoperator(*i)){
if(isempty(&s))
push(&s, *i);
else {
n = pop(&s);
while(priotity(n) >= priotity(*i)){
*p = n;
p++;
*p = ' ';
p++;
n = pop(&s);
}
push(&s, n);
push(&s, *i);
}
}
i++;
}
while(!isempty(&s)){
n = pop(&s);
*p = n;
p++;
*p = ' ';
p++;
}
p--;p--;
*p = '\0';
}
int evaluate(char *pexp){
int o1, o2;
char *p;
stack s;
empty_stack(&s);
p = pexp;
while(*p != '\0'){
if(isoperator(*p)){
o1 = pop(&s);
o2 = pop(&s);
switch(*p){
case '+':
push(&s, o1+o2);
break;
case '-':
push(&s, o1-o2);
break;
case '/':/*-> modified*/
push(&s, o2/o1);
break;
case '*':
push(&s, o1*o2);
break;
case '%':/*->modified*/
push(&s, o2%o1);
break;
}
}
else if(isdigit(*p)){
push(&s, atoi(p));
while(isdigit(*p))p++;
}
p++;
}
return pop(&s);
}
int isoperator(char c){
if(c=='+' || c=='-' || c=='*' || c=='/' || c=='%')
return 1;
else
return 0;
}
int isdigit(char c){
if(c=='1' || c=='2' || c=='3' || c=='4' || c=='5' || c=='6' ||
c=='7' || c=='8' || c=='9' || c=='0')
return 1;
else
return 0;
}
int priotity(char o){
if(o=='*' || o=='/' || o=='%')
return 2;
else if(o=='+' || o=='-')
return 1;
return 0;
}
void empty_stack(stack *s){
s->top = _EMPTY_STACK;
}
int isempty(stack *s){
if(s->top == _EMPTY_STACK)return 1;
else return 0;
}
int push(stack *s, int e){
if(s->top == (_FULL_STACK - 1)){
return -1;
}
else{
(s->top)++;
s->elements[s->top] = e;
return 0;
}
}
int pop(stack *s){
if(isempty(s))
return -1;
else{
int ret = s->elements[s->top];
--s->top;
return ret;
}
}