/**** CHAPTER 6 - PROGRAM 10 * * Model of a simple calculator * Scans data lines consisting of a binary operator and a right * operand. Using the current value of the accumulator (initial value * zero) as the left operand, program calculates and displays new * accumulator value. * * Recognized operations are addition (+), subtraction (-), * multiplication (*), division (/), and exponentiation (^). */ #include #include typedef enum {false, true} boolean; /* * Input a one-character operator and a number from a line of data. * If a valid number is scanned and the character is one of these-- * + - * / ^ -- return 1. Otherwise return 0. Discard the rest of the * input line. * Post-condition: operator contains the symbol for the operation to perform. operand contains the value to be manipulated. */ boolean scan_data (char *operator, /* output - the operator */ double *operand); /* output - the operand */ /* * Apply op using *accum as left operand and operand as right operand, * storing result in *accum. * Pre: op is + or - or * or / or ^ */ void do_next_op (char op, /* input - operator */ double operand, /* input - operand */ double *accump); /* input/output - accumulated value */ /* * Verify that ch is one of the characters + - * / ^ */ int valid_op (char ch); int main(void) { double accum = 0; /* Accumulator */ char op; /* symbol for arithmetic operator to be applied */ boolean scan_status; /* Successful scan flag */ double operand; /* operand */ printf("Repeatedly enter operator and operand. Enter \nq 0\nto quit.\n"); scan_status = scan_data(&op, &operand); while (scan_status) { do_next_op(op, operand, &accum); printf("result so far is %.1f\n", accum); scan_status = scan_data(&op, &operand); } printf("final result is %.2f\n", accum); return (0); } int valid_op(char ch) { int valid; switch (ch) { case '+': case '-': case '*': case '/': case '^': valid = 1; break; default: valid = 0; } return (valid); }