Hatena::Groupcprogramming

C Study Diary

2008-12-12

c4ex3calculator.cpp

16:30

Given the basic framework, it's straightforward to extend the Polish notation calculator. Add the modulus ( % ) operator and provisions for negative numbers.

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

#define MAX 100
#define NUM '#'

int sp=0, i=0;
double stack[MAX];
double number=0.0;
char s[MAX];

void push(double n){
	
	if(sp==MAX) {
		printf("exceed max stack space!\n");
	}else{
		stack[sp++]=n;
	}
}

double pop(){
	
	if(sp>0) return stack[--sp];  /* --sp ! */
	else {
		printf("stack is empty!\n");
		return 0.0;
	}	
}

/* process input - Polish notation */
int getinput(){
	
	int c, nc;
	int sign = 1;
	double frac = 0.0, p = 1.0;
	while((c=s[i++])!='\0'){	
		/* operator */
		if(c=='+' || c=='*' || c=='/' || c=='%') {
			return c;
		}	
		if(c=='-') {
			if((nc=s[i])!=' '){
				sign=-1;
			}
			else {
				return c;
			}	
		}	
		/* number */
		if(isdigit(c) || c=='.') {
			while(isdigit(c)) {
				number=number*10.0+(c-'0');
				c=s[i++];
			}	
			if(c=='.'){
				c=s[i++];
				while(isdigit(c)) {
					p*=0.1;
					frac+=(c-'0')*p;
					c=s[i++];
				}
			}			
			i--;
			number = (number+frac)*sign;
			return NUM;
		}	
	}
	return EOF;

}

int main(){
	
	int c;
	double result=0, t1, t2;
	
	printf("input formular:\n");
	gets(s);

	/* operation  */
	while((c=getinput())!=EOF){
		switch(c){
			case '+': t1=pop(); t2=pop(); push(t1+t2); break;
			case '-': t1=pop(); t2=pop(); push(t2-t1); break;
			case '*': t1=pop(); t2=pop(); push(t2*t1); break;
			case '/': t1=pop(); t2=pop(); push(t2/t1); break;
			case '%': t1=pop(); if((t2=pop())!=0) push((int)t2%(int)t1); else printf("0 cannot be divided. \n"); break;	
			case NUM:  push(number); number=0; break;
			default: printf("error input! \n"); return -1;						
		}		
	}
	printf("%s = ",s);
	printf("%f\n",pop());
 	
}	

Run:

$ ./c4ex3calculator.exe
input formular:
2 3 + 4.4554 * 56.1 /
2 3 + 4.4554 * 56.1 / = 0.397094

$ ./c4ex3calculator.exe
input formular:
432 100 % 2 * 0+
432 100 % 2 * 0+ = 64.000000

moritamorita2008/12/15 20:29How about wrong inputs? for example, "1++1".
In general, you should be careful to handle user inputs.

annancyannancy2008/12/16 13:01Thanks for the comment. Yeah, this program is weak at wrong input. When error operator inputted, user will get 'stack empty error'. I'll try to improve it in the next version.