yag Site Admin
註冊時間: 2007-05-02 文章: 689
2704.11 果凍幣
|
發表於: 2007-6-4, PM 5:42 星期一 文章主題: neilshih的C語言版後置式(postfix)計算機 |
|
|
neilshih 寫到: |
這是我在學校自己寫的後置式計算機
代碼: |
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int getnextword(char s[], int idx, char w[]);
int push(int x);
int pop(void);
int stack[100];
int sp = 0;
int main(void){
char word[64];
char str[128];
char op;
int i;
int a, b, c;
while(strcmp(gets(str), "quit")){
for(i = 0; (i = getnextword(str, i, word)) >= 0;){
if(isdigit(word[0]))
push(atof(word));
else{
op = word[0];
b = pop();
a = pop();
switch(op){
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
if(b == 0)
printf("\n\aDivision by zero error!\n");
else
c = a / b;
break;
default:
printf("\n\aIllegal operation!\n");
break;
}
push(c);
}
}
printf("%d\n", pop());
}
}
int getnextword(char s[], int idx, char w[]){
int i = 0;
while(s[idx] == ' ')
++idx;
while(s[idx] != ' ' && s[idx] != '\0' && s[idx] != '\n')
w[i++] = s[idx++];
w[i] = '\0';
return i == 0 ? -1 : idx;
}
int push(int x){
if(sp < 100)
return stack[sp++] = x;
else{
printf("error:stack full can't push %g\n", x);
return 0;
}
}
int pop(void){
if(sp > 0)
return stack[--sp];
else{
printf("error:stack empty\n");
return 0;
}
} |
|
|
|