Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Hau to
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <conio.h>
- int stack [1000];
- int top;
- // Tính giá tr. c.a bi.u th.c
- int eval (char *s);
- // Ki.m tra có ph.i phép toán
- int isop (char op);
- // Thao tác ð.y ra c.a ngãn x.p
- int pop (void);
- // Thao tác ð.y vào c.a ngãn x.p
- void push (int a);
- // Th.c hi.n phép toán
- int do_op (int a, int b, char op);
- int main (void){
- char expression[80];
- int value;
- printf ("Nhap vao xau bieu thuc: ");
- gets(expression);
- printf ("\nBieu thuc nhap vao: %s", expression);
- value=eval (expression);
- printf ("\nGia tri cua bieu thuc = %i", value);
- getch();
- return 0;
- }
- int eval (char *s){
- char *ptr;
- int first, second, c;
- ptr = strtok (s, " ");
- top = -1;
- while (ptr) {
- if (isop (*ptr)) {
- second = pop(); first = pop();
- c = do_op (first, second, *ptr);
- push(c);
- }
- else { c = atoi(ptr); push(c);
- }
- ptr = strtok (NULL, " ");
- }
- return (pop ());
- }
- int do_op (int a, int b, char op){
- int ans;
- switch (op) {
- case '+':
- ans = a + b;
- break;
- case '-':
- ans = a - b;
- break;
- case '*':
- ans = a * b;
- break;
- }
- return ans;
- }
- int pop (void){
- int ret;
- ret = stack [top];
- top--;
- return ret;
- }
- void push (int a){
- top++;
- stack [top] = a;
- }
- int isop (char op){
- if (op == '+' || op == '-' || op == '*')
- return 1;
- else
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment