MyException - 我的异常网
当前位置:我的异常网» C# » 利用字符串进行数值计算的有关问题

利用字符串进行数值计算的有关问题(2)

www.myexceptions.net  网友分享于:2013-12-26  浏览:17次

//23|56|102|100|-|/|*|36|24|-|8|6|-|/|*|+ "
private string calculateparenthesesexpressionex(string expression)
{
//定义两个栈
arraylist operandlist =new arraylist();
float operand1;
float operand2;
string[] operand3;

expression = expression.replace( " ", " ");
operand3 = expression.split(convert.tochar( "| "));

for(int i = 0;i < operand3.length;i++)
{
if(char.isnumber(operand3[i],0))
{
operandlist.add( operand3[i].tostring());
}
else
{
//两个操作数退栈和一个操作符退栈计算
operand2 =(float)convert.todouble(operandlist[operandlist.count-1]);
operandlist.removeat(operandlist.count-1);
operand1 =(float)convert.todouble(operandlist[operandlist.count-1]);
operandlist.removeat(operandlist.count-1);
operandlist.add(calculate(operand1,operand2,operand3[i]).tostring()) ;
}

}


return operandlist[0].tostring();
}



//判断两个运算符优先级别
private bool verifyoperatorpriority(string operator1,string operator2)
{

if(operator1== "* " && operator2 == "+ ")
return true;
else if(operator1== "* " && operator2 == "- ")
return true;
else if(operator1== "/ " && operator2 == "+ ")
return true;
else if(operator1== "/ " && operator2 == "- ")
return true;
else
return false;
}

//计算
private float calculate(float operand1, float operand2,string operator2)
{
switch(operator2)
{
case "* ":
operand1 *= operand2;
break;
case "/ ":
operand1 /= operand2;
break;
case "+ ":
operand1 += operand2;
break;
case "- ":
operand1 -= operand2;
break;
default:
break;
}
return operand1;
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有