含函数的四则运算(采用后缀表达式)

  • 格式:txt
  • 大小:16.15 KB
  • 文档页数:6

using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;


namespace Arithmetic
{
public partial class Form1 : Form
{
private static Dictionary _operatorLevel;
private static Dictionary _functionLevel;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//string[] str = ToStandardInfix(InsertBlank(textBox1.Text));
//textBox4.Text = str;
//textBox2.Text = InfixToPostfix(InsertBlank(ToStandardInfix(InsertBlank(textBox1.Text))));
textBox3.Text=Evaluate(textBox1.Text).ToString();
}

private static double Evaluate(string expression)
{
string str0 = InsertBlank(expression);
string[] str = ToStandardInfix(InsertBlank(expression));
string str2 = InfixToPostfix(str);
return GetResult(str2);
}

public static string InfixToPostfix(string[] list)
{
StringBuilder result = new StringBuilder();
Stack stack = new Stack();

for (int i = 0; i < list.Length ; i++)
{
string current = list[i];

//if (Regex.IsMatch(current, @"^[-]?\d+(\.\d+)?")) //数字/值
//{
// result.Append(current + " ");
//}

//else if (Regex.IsMatch(current, @"[a-z|A-Z][a-z|A-Z|0-9]*")) //函数
//{
// result.Append(current + " ");
//}
if(current.Contains(","))
{
result.Append(current + " ");
}
else if (FunctionLevel.ContainsKey(current))
{

stack.Push(current);
continue;
}
else if (OperatorLevel.ContainsKey(current))
{
if (stack.Count > 0)
{
var prev = stack.Peek();

if (prev == "(")
{
stack.Push(current);
continue;
}
if (current == "(")
{
stack.Push(current);
continue;
}

if (current == ")")
{
while (stack.Count > 0 && stack.Peek() != "(")
{

result.Append(stack.Pop() + " ");
}
//Pop the "("
if (stack.Count > 0)
stack.Pop();
continue;
}
if (OperatorLevel[current] < OperatorLevel[prev])
{
while (stack.Count > 0)
{
var top = stack.Pop();
if (top != "(" &&
top != ")")
{
result.Append(top + " ");
}
else
{
break;
}
}
stack.Push(current);
}
else
{
stack.Push(current);
}
}
else
{
stack.Push(current);
}
}
else
{
result.Append(current + " ");
}
}

if (stack.Count > 0)
{
while (stack.Count > 0)
{
var top = stack.Pop();
if (top != "(" && top != ")")
{
result.Append(top + " ");
}
}
}
return result.ToString();
}

public static object[] ParseParams(string theParams)
{
string[] ps = SplitParams(theParams);
// string[] ps = theParams.Split(',');
int theCount = ps.Count();
object[] result = new object[theCount];
for (int i = 0; i < theCount; i++)
{
result[i] = Evaluate(ps[i]);
}
return ps;
}

private static string[] SplitParams(string paramString) //按“,”来分开函数参数,但不分开参数中函数的参数
{
List list = new List();
// string raw2 = InsertBlank(paramString);
string raw2 = paramString;
//string[] elements = ShrinkStrings(raw2.Split(',',' '));
int pos=0;
int pos1=0;
while (true)
{
pos1 = raw2.IndexOf(',', pos);
if (pos1 == -1) break;
if (!IsInParentheses(raw2, pos1))
{
raw2=raw2.Remove(pos1, 1);
raw2=raw2.Insert(pos1, "#");
}
pos =

pos1+1;
}
string[] elements = ShrinkStrings(raw2.Split('#'));

//int theCount = elements.Count();

//int innerParentheses = 0;

//for (int i = 0; i < theCount; i++)
//{
// if (IsFunction(elements[i]))
// {

// list.Add(elements[i]);
// i +=2;
// StringBuilder sb = new StringBuilder();
// innerParentheses = 0;
// while (elements[i] != ")" || innerParentheses != 0)
// {
// if (elements[i] == "(")
// {
// innerParentheses++;
// sb.Append(elements[i]);
// }
// else if (elements[i] == ")")
// {
// innerParentheses--;
// sb.Append(elements[i]);
// }
// else
// {
// sb.Append(elements[i]);
// sb.Append(",");
// }
// i++;

// }
// sb.Remove(sb.Length - 1, 1);
// list.Add(sb.ToString());
// }

// else
// {
// list.Add(elements[i]);

// }

//}
// return list.ToArray();
return elements;
}

public static bool IsInParentheses(string source, int position) //看一个字符是否处于括号中(一般为函数中)
{
int innerParenthesis = 0;
for (int i = position - 1; i >= 0; i--)
{
if (source[i] == ')') innerParenthesis++;
if (source[i] == '(')
{
if (innerParenthesis == 0) return true;
else innerParenthesis--;
}
}
return false;
}

public static bool IsFunction(string str)
{
if (str == "sin") return true;
else if (str == "GetMax") return true;
return false;
}

public static string[] ShrinkStrings(string[] strs)
{
List list = new List();
foreach (string str in strs)
{
if (str != "") list.Add(str);
}
return list.ToArray();
}

//化成标准的中缀表达式,主要是对函数进行修改 如fun(a,b,c)=>(0 fun a,b,c)
public static string[] ToStandardInfix(string raw)
{
// StringBuilder sb = new StringBuilder();
List list = new List

g>();
string raw2 = InsertBlank(raw);
string[] elements = ShrinkStrings(raw2.Split(' '));
int theCount = elements.Count();

int innerParentheses=0;

for (int i = 0; i < theCount; i++)
{
if (IsFunction(elements[i]))
{
list.Add("(");
list.Add("0");
list.Add(elements[i]);
i+=2; //略过函数的左括号“(”
StringBuilder sb = new StringBuilder();
innerParentheses=0;
while(elements[i]!=")" || innerParentheses!=0)
{
if(elements[i]=="(")
{
innerParentheses++;

}
if(elements[i]==")")
{
innerParentheses--;

}
sb.Append(elements[i]);
i++;

}
list.Add(sb.ToString());
list.Add(elements[i]);
}

else
{
list.Add(elements[i]);
//if (!waitclose)
//{
// list.Add(elements[i]);
//}
//else
//{
// if (elements[i] == "(")
// {
// innerParentheses++;
// sb.Append(elements[i]);
// }
// else
// {
// if (elements[i] == ")")
// {
// if (innerParentheses > 0)
// {
// innerParentheses--;
// sb.Append(elements[i]);
// }
// else
// {
// elements[i] = ")";
// waitclose = false;
// innerParentheses = 0;
// string sstr=sb.ToString().Trim();
// list.Add(sstr);
// i++;
// }
// }
// else
// {
// sb.Append(elements[i]);
// }
// }

}

}

return list.ToArray();

}


public static Dictionary OperatorLevel
{
get
{
if (_operatorLevel == null)
{
_operatorLevel = new Dictionary();
_operatorLevel.Add("+", 0);
_operatorLevel.Add("-", 0);
_operatorLevel.Add("(", 2);
_operatorLevel.Add("*", 1);
_operatorLevel.Add("/", 1);
_operatorLevel.Add(")", 0);

}
return _operatorLevel;
}
}

public static Dictionary FunctionLevel
{
get
{
if (_functionLevel == null)
{
_functionLevel = new Dictionary();
_functionLevel.Add("sin", 2);
_functionLevel.Add("GetMax", 2);
}
return _functionLevel;
}
}

public static double GetValue(double left, double right, string _operator)
{
switch (_operator)
{
case "+":
return left+right;
case "-":
return left-right;
case "*":
return left*right;
case "/":
return left/right;

}
return 0;
}

public static double GetFunctionValue(object[]parameters, string fName)
{
switch (fName)
{

case "sin":
return Math.Sin(Evaluate((string)parameters[0]));
case "GetMax":
double a = Evaluate((string)parameters[0]);
double b = Evaluate((string)parameters[1]);
double c = Evaluate((string)parameters[2]);
return GetMax(Evaluate((string)parameters[0]), Evaluate((string)parameters[1]), Evaluate((string)parameters[2]));
}
return 0;
}

public static double GetMax(double num1, double num2, double num3 )
{
double theMax = num1;
if (num2 > theMax) theMax = num2;
if (num3 > theMax) theMax = num3;
return theMax;
}


public static double GetResult(string source)
{
Stack stack = new Stack();

var list = ShrinkStrings(source.Split(' '));
for (int i = 0; i < list.Length; i++)
{
string current = list[i];
//if (Regex.IsMatch(current, @"^\d+(\.\d+)?"))
//{
// stack.Push(current);

//}
if (OperatorLevel.ContainsKey(current))
{
string strRight = (stack.Pop());
string strLeft = (stack.Pop());

double right = double.Parse(strRight);
double left = double.Parse(strLeft);
stack.Push(GetValue(left, right, current).ToString());

}
else if (FunctionLevel.ContainsKey(current))
{
string strRight = (stack.Pop());
string strLeft = (stack.Pop());
object[] ps = ParseParams(strRight);
stack.Push(GetFunctionValue(ps, current).ToString());

}
else
{
stack.Push(current);
}
}
return double.Parse(stack.Pop());
}

public static string InsertBlank(string source)
{
StringBuilder sb = new StringBuilder();
var list = source.ToCharArray();
foreach (var temp in list)
{
if (OperatorLevel.ContainsKey(temp.ToString()))
{
sb.Append(' ');
sb.Append(temp.ToString());
sb.Append(' ');
}
else
{
sb.Append(temp);
}
}
return sb.ToString();
}


}

}

下载文档原格式

  / 6
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。