forked from Cherish599/AchaoCalculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculater.cpp
95 lines (95 loc) · 1.63 KB
/
Calculater.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
#include"Calculater.h"
void cal_data::div_str(string& expr)
{
int size = 0;
double num = 0;
for(string::size_type ix=0;ix<expr.size();)
{
if (is_number(expr.at(ix)))
{
size = num_size(expr, ix);
num = stod(expr.substr(ix, ix + size));
num_stk.push(num);
ix += size;
}
else
{
if (oper_stk.empty())
{
oper_stk.push(expr.at(ix));
}
else if (oper_priority(expr.at(ix)) <= oper_priority(oper_stk.top()))
{
calculate();
oper_stk.push(expr.at(ix));
}
else
{
oper_stk.push(expr.at(ix));
}
++ix;
}
}
while (!oper_stk.empty())
{
calculate();
}
cout << expr<<"=" <<static_cast<int>( num_stk.top()) << endl;
//num_stk.pop();
}
bool cal_data::is_number(char c)
{
string numbers = "0123456789";
if (numbers.find(c) != string::npos)
{
return true;
}
else
return false;
}
string::size_type
cal_data::num_size(string& expr, string::size_type pos)
{
string numbers = "0123456789";
string::size_type size;
size = expr.find_first_not_of(numbers, pos) - pos;
return size;
}
int cal_data::oper_priority(char c)
{
if (c == '+' || c == '-')
return 0;
else if (c == '*')
return 1;
else if (c == '/')
return 2;
}
void cal_data::calculate()
{
double left_num=0;
double right_num=0;
double result = 0;
char op = oper_stk.top();
oper_stk.pop();
right_num=num_stk.top();
num_stk.pop();
left_num = num_stk.top();
num_stk.pop();
if (op == '+')
{
result = left_num + right_num;
}
else if (op == '-')
{
result = left_num - right_num;
}
else if (op == '*')
{
result = left_num * right_num;
}
else if(op=='/')
{
result = left_num / right_num;
}
num_stk.push(result);
}