-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evaluate.cs
128 lines (111 loc) · 3.31 KB
/
Evaluate.cs
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
public class EvaluateClass
{
private bool HasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
{
return false;
}
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
{
return false;
}
if (op1 == '^' && (op2 == '*' || op2 == '/' || op2 == '+' || op2 == '-'))
{
return false;
}
else
{
return true;
}
}
private double ApplyOp(char op, double b, double a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
{
throw new
System.NotSupportedException(
"Cannot divide by zero");
}
return a / b;
case '^':
return Math.Pow(a, b);
}
return 0;
}
public double Evaluate(string expression, int digits)
{
char[] tokens = expression.ToCharArray();
Stack<double> numbers = new Stack<double>();
Stack<char> ops = new Stack<char>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i] == ' ')
{
continue;
}
if (tokens[i] == 'e')
{
numbers.Push(2.71828182846);
}
if ((tokens[i] >= '0' && tokens[i] <= '9') || (tokens[i] == '.' || tokens[i] == ','))
{
System.Text.StringBuilder number = new System.Text.StringBuilder();
while (i < tokens.Length && ((tokens[i] >= '0' && tokens[i] <= '9') || tokens[i] == '.'))
{
number.Append(tokens[i++]);
}
numbers.Push(double.Parse(number.ToString()));
i--;
}
else if (tokens[i] == '(')
{
ops.Push(tokens[i]);
}
else if (tokens[i] == ')')
{
while (ops.Peek() != '(')
{
numbers.Push(ApplyOp(ops.Pop(), numbers.Pop(), numbers.Pop()));
}
ops.Pop();
}
else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/' || tokens[i] == '^')
{
while (ops.Count > 0 && HasPrecedence(tokens[i], ops.Peek()))
{
numbers.Push(ApplyOp(ops.Pop(), numbers.Pop(), numbers.Pop()));
}
ops.Push(tokens[i]);
}
}
while (ops.Count > 0)
{
numbers.Push(ApplyOp(ops.Pop(), numbers.Pop(), numbers.Pop()));
}
return double.Round(numbers.Pop(), digits, MidpointRounding.AwayFromZero);
}
public string f(string exp, double x)
{
char oldChar = 'x';
string strVal = x.ToString();
string newExp = "";
string[] array = exp.Split(oldChar);
for (int i = 0; i < array.Length - 1; i++)
{
newExp += array[i];
newExp += strVal;
}
newExp += array[array.Length - 1];
return newExp;
}
}