一桁だけの逆ポーランド計算機(変数も使えるよ)
変数も使えるようにしてみました。
ただし変数名は一文字(a〜z)
おまけで階乗計算ができます(5!とかa!とか)
使い方は
「a 5 =」で変数aに5が代入されます(aに5を代入)
a=5 b=7 (a+5)*b
という計算は
C:\test>calc >a 5 = =5 >b 7 = =7 >a 5 + b * =70 >5! =120
となります
これもコンパイル結果を置いておきます
http://props.at.infoseek.co.jp/calc2.exe
http://props.at.infoseek.co.jp/calc2.cpp
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int stack[1024]; int type[1024]; int sp=0; char buf[1024]; int bp=0; int err=0; int word['z'-'a'+1]; void push(int t,int v) { if(sp>=1024) { err=2; return; } type[sp]=t; stack[sp++]=v; } int pop() { if(sp<=0) { err=2; return 0; } if(type[--sp]==0) return stack[sp]; else return word[stack[sp]]; } void assign(int v) { if(type[--sp]==0) { err=1; return; } word[ stack[sp] ] = v; push(1,stack[sp] ); } int fact(int x) { if(x==1) return 1; return x*fact(x-1); } void parse() { sp=bp=err=0; for(;;) { int c=buf[bp++]; if( c==0 ) { printf("=%d\n",pop());return; } if( c==' ' ) continue; // printf("%c ",c); if( c=='=' ) { int x=pop();assign(x); } else if( isalpha(c) ) { push(1,c-'a'); } else if( isdigit(c) ) { push(0,c-'0'); } else if( c=='+' ) { int x=pop();int y=pop();push(0,x+y); } else if( c=='-' ) { int x=pop();int y=pop();push(0,y-x); } else if( c=='*' ) { int x=pop();int y=pop();push(0,y*x); } else if( c=='/' ) { int x=pop();int y=pop();push(0,y/x); } else if( c=='!' ) { int x=pop();int y=fact(x);push(0,y); } if(err>0) { printf("ERROR\n");break; } } } void main() { for(;;) { printf(">"); fgets(buf, sizeof(buf), stdin); if( buf[0]=='q' ) break; parse(); } }