|
|
1.1 root 1: //
2: // CalcEngine -- mem
3: // A general C++ class that directly supports a calculator interface
4: //
5: // You may freely copy, distribute and reuse the code in this example.
6: // NeXT disclaims any warranty of any kind, expressed or implied, as to
7: // its fitness for any particular use.
8: //
9: // Created 8-21-90
10: //
11: extern "Objective-C"
12: {
13: #import <objc/error.h>
14: }
15:
16: #import "CalcEngine.h"
17:
18: // Create an instance of the class and initialize flags for start-up
19: CalcEngine::CalcEngine()
20: {
21: //the buffer that holds the first number entered
22: accumulator = 0;
23:
24: //the current operator
25: op = 0;
26: }
27:
28: // Clear the state of the calculator engine.
29: void CalcEngine::clear()
30: {
31: setOperation(0);
32: accumulator = 0;
33: }
34:
35: // Set the current operation (+ - * / ), 0 is no operation.
36: void CalcEngine::setOperation(int whichOp)
37: {
38: op = whichOp;
39: }
40:
41: // Called when one of the operation keys is pressed.
42: double CalcEngine::operationKeys(int whichOp, double firstNum)
43: {
44: double result;
45:
46: switch(whichOp){
47: case DIVIDE: // Indicates a series of numbers and
48: case MULTIPLY: // operations. For example: 1 + 2 + 3 + ...
49: case SUBTRACT:
50: case ADD:
51: {
52: if (op)
53: result = equalsKey(firstNum);
54: else
55: result = firstNum;
56: setOperation(whichOp);
57: accumulator = result;
58: break;
59: }
60: default: // Indicates first number has just been
61: { // entered.
62: result = 0;
63: break;
64: }
65: }
66: return result;
67: }
68:
69: // Do the actual calculation. This is called when the equals key is pressed or
70: // when an operation key is pressed in a series of numbers.
71: double CalcEngine::equalsKey(double secondNum)
72: {
73: double result;
74:
75: switch(op){
76: case DIVIDE:
77: {
78: if(secondNum == 0) {
79: clear();
80: NX_RAISE(0, "divideByZero", 0);
81: }
82: result = accumulator / secondNum;
83: break;
84: }
85: case MULTIPLY:
86: {
87: result = accumulator * secondNum;
88: break;
89: }
90: case SUBTRACT:
91: {
92: result = accumulator - secondNum;
93: break;
94: }
95: case ADD:
96: {
97: result = accumulator + secondNum;
98: break;
99: }
100: default:{
101: result = secondNum;
102: break;
103: }
104: }
105: clear();
106: return result;
107: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.