0
我是个C#初学者在这里,我要带去从文本字符串和运用以下算法中,但操作数和运算符不工作的断裂..执行算术运算在字符串在C#中
string cal = "225+699";
char[] all= cal.ToCharArray();
int i=0,j=0;
while (all[i] != '+' || all[i] != '-' || all[i] != '/' || all[i] != 'x')
{
j++;
} // first operator check
char op = all[j + 1]; // operator save
char[] part1 = new char[j];
for (i = 0; i <= j; i++)
{
part1[i] = all[i];
}
string inp = Convert.ToString(part1);
float a = float.Parse(inp); // first operand
int l=cal.Length-(j+1);
char[] part2 = new char[l];
int c = 0;
for (i = j + 1; i <= cal.Length; i++)// starts after operator
{
part2[c] = all[i];
c++;
}
string h = Convert.ToString(part2);
float b = float.Parse(h); // other operand
如果你的算法的目的只是解析算术表达式,你可以使用C#的一些内置特性,比如'ScriptControl()'。在这里看到一个例子:http://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net – niculare 2013-03-04 20:45:32