Capstone: CLI calculator
| The goal | |
| Design | |
| Build steps |
The goal
Build a calculator that takes two numbers and an operator from the command line, computes the result, and prints it with an edited picture. It uses ACCEPT FROM ARGUMENT-VALUE, EVALUATE, and DIVIDE with ON SIZE ERROR.
Design
Declare three argument fields and one result field in WORKING-STORAGE. The operator field is PIC X, and the result uses an edited picture so the output looks like a pocket calculator:
01 WS-LEFT PIC S9(9)V99.
01 WS-RIGHT PIC S9(9)V99.
01 WS-OP PIC X.
01 WS-RESULT PIC -$$,$$$,$$9.99.
Build steps
Accept the three arguments, move NUMVAL conversions into the numeric fields, then EVALUATE the operator. Add, SUBTRACT, MULTIPLY, and DIVIDE each in one WHEN branch, with ON SIZE ERROR catching division by zero. Finish by DISPLAYing the edited result and moving 0 into RETURN-CODE. Compile with cobc -x -free, run it with three arguments, and test the divide-by-zero path before calling it done.
Next: Capstone: fixed-width file processor
Article author: Arthur Isaev