|
CS 456 - Systems Programming
Spring 2024
|
Displaying ./code/apr17/rpn.c
// rpn.c: reverse polish notation calculator
#include "rpn.h"
int main(void) {
//get variable declarations
int type; //type of input
char input[MAXOPSIZE]; //stores the input
double op2; //stores a number
while ( (type = getop(input, MAXOPSIZE)) != EOF ) {
switch ( type ) {
case NUMBER: //we get a number
push(atof(input)); // convert number to an integer, push it onto the stack
break;
case '+':
push(pop() + pop()); // pop the two numbers from the stack and add them
break;
case '*':
push(pop() * pop()); // pop the top two numbers from the stack and multiply them
break;
case '-':
op2 = pop(); //pop number on top of the stack, stores it in op2
push(pop() - op2); //pop next number, subtract op2 from that number, push that to top stack
break;
case '/':
op2 = pop(); // pop top of stack, store in op2
if ( op2 == 0.0 ) // check if this is Zero, as we dont want a divide by Zero error
printf("Divide by zero.\n");
else
push(pop() / op2); // pop next number, divide it by op2
break;
case '=':
printf("Top: %f\n", push(pop())); // essentally taking what's on top of the stack, printing it, then pushing it back
break;
case 'c':
clear_stack(); //clears the stack
break;
case TOOBIG:
printf("Input too large: '%s'\n", input); // input is too large
break;
default:
printf("Unknown command: '%c'\n", type); //unknown command entered
}
}
// end while
return 0;
}
|