Hi, this is a simple reverse polish notation calulator in C it takes the input as postfix and and shows the result. this is very basic code I not added any functions but I may do in time. One rule of the code is that all numbers and operators must be seperated by a space. Anyway hope you find it intresting if you like more information on RPN you can check out https://en.wikipedia.org/wiki/Reverse_Polish_notation
Code:#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define MAX_EXPR 1024 #define MAX_TOKEN 30 #define MAX_STACK 100 #define TRUE 1 #define FALSE 0 //Points to top of stack. int st =-1; //Stack holds the values. float STACK[MAX_STACK] = {0.0}; int is_num(char *src){ //Function to test if we have a number works for decimal places int x = 0; int ok = TRUE; while(x < strlen(src)){ //Test for digit or dot if(!isdigit(src[x]) && src[x] != '.'){ ok = FALSE; break; } x++; } return ok; } int is_op(char op){ if(op == '+' || op == '-' || op == '*' || op == '/'){ return TRUE; } return FALSE; } void Push(float v){ STACK[++st] = v; } float Pop(){ return STACK[st--]; } float calc_rpn(char *expr){ char zToken[MAX_TOKEN]; char src[MAX_EXPR]; float a = {0.0}; float b = {0.0}; int x = 0; int y = 0; st = -1; //Make a copy of expr strcpy(src,expr); //Append last space so the string will split properly and not miss the end of the string. strcat(src," "); while(x < strlen(src)){ //Check for space if(src[x] == ' '){ //Zap end of string. zToken[y] = '\0'; //Check for number. if(is_num(zToken) == TRUE){ //Push the number onto the stack Push(atof(zToken)); }else{ //Process operators switch(zToken[0]){ case '+': a = Pop(); b = Pop(); Push(b+a); break; case '-': a = Pop(); b = Pop(); Push(b-a); break; case '*': a = Pop(); b = Pop(); Push(b*a); break; case '/': a = Pop(); b = Pop(); Push(b/a); break; } } //Reset y y = 0; }else{ //Build string buffer. zToken[y] = src[x]; //INC string buffer index y++; } x++; } //Clear up memset(zToken,0,sizeof zToken); memset(src,0,sizeof src); //Pop off result. return Pop(); } int main() { //5 + 5 / (5 * 3) + 120 - (4+8) float c = calc_rpn("5 5 5 3 * / + 120 + 4 8 + -"); //Print result printf("%f\n",c); //Clear stack memset(STACK,0,sizeof STACK); return 0; }




Reply With Quote
