-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculation.cpp
111 lines (97 loc) · 2.21 KB
/
Calculation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
using namespace std;
class Operation {
protected:
double numberA;
double numberB;
public:
virtual double getResult() {
return 0;
};
void setNumberA(double a) {
numberA = a;
}
void setNumberB(double b) {
numberB = b;
}
double getNumberA() {
return numberA;
}
double getNumberB() {
return numberB;
}
};
class OperationAdd : public Operation {
public:
double getResult() {
return numberA + numberB;
}
};
class OperationSub : public Operation {
public:
double getResult() {
return numberA - numberB;
}
};
class OperationMul : public Operation {
public:
double getResult() {
return numberA * numberB;
}
};
class OperationDiv : public Operation {
public:
double getResult() {
if(-0.00000001 < numberB && numberB < 0.00000001) {
cout << "除零错误" << endl;
return 0;
}
return numberA / numberB;
}
};
class OperationFactory {
private:
Operation* operation;
public:
OperationFactory():operation(NULL){}
~OperationFactory() {
delete operation;
}
Operation* CreateOperate(char o) {
switch(o) {
case '+':
operation = new OperationAdd();
break;
case '-':
operation = new OperationSub();
break;
case '*':
operation = new OperationMul();
break;
case '/':
operation = new OperationDiv();
break;
default:
cout << "无法识别该符号" << endl;;
}
return operation;
}
};
int main(int argc, const char * argv[]) {
double numberA;
double numberB;
char operate;
cout<<"输入数字A: ";
cin>>numberA;
cout<<"运算符(+ - * /): ";
cin>>operate;
cout<<"输入数字B: ";
cin>>numberB;
OperationFactory factory;
Operation* operation;
operation = factory.CreateOperate(operate);
operation->setNumberA(numberA);
operation->setNumberB(numberB);
cout<<"计算结果:"<<operation->getResult()<<endl;
return 0;
}