欢迎光临
我们一直在努力

字符串表达式计算C#程序设计-.NET教程,C#语言

建站超值云服务器,限时71元/月

在编程应用程序过程中,有时需要字符串表达式的值。如字符串:”23+56/(102-100)*((36-24)/(8-6))”,结果=191。
      根据数据结构栈的应用介绍,通过把表达式由中序式转换成后序式,再用栈来进行计算。如上述字符串表达式:”23+56/(102-100)*((36-24)/(8-6))”,转换为后序时为:”23|56|102|100|-|/|*|36|24|-|8|6|-|/|*|+”(其中字符”|”为分隔符)。
      本程序代码如下:在visual .net 2003 +winxp下编译通过。

using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.data;

namespace stringexpressioncalculate
{
 /// <summary>
 /// form1 的摘要说明。
 /// </summary>
 public class form1 : system.windows.forms.form
 {

  private system.windows.forms.textbox textbox1;
  private system.windows.forms.button button1;
  private system.windows.forms.textbox textbox2;
  private system.windows.forms.label label1;
  private system.windows.forms.label label2;
 
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private system.componentmodel.container components = null;

  public form1()
  {
   //
   // windows 窗体设计器支持所必需的
   //
   initializecomponent();

   //
   // todo: 在 initializecomponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.dispose();
    }
   }
   base.dispose( disposing );
  }

  #region windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 – 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void initializecomponent()
  {
   this.textbox1 = new system.windows.forms.textbox();
   this.button1 = new system.windows.forms.button();
   this.textbox2 = new system.windows.forms.textbox();
   this.label1 = new system.windows.forms.label();
   this.label2 = new system.windows.forms.label();
   this.suspendlayout();
   //
   // textbox1
   //
   this.textbox1.location = new system.drawing.point(114, 33);
   this.textbox1.name = “textbox1”;
   this.textbox1.size = new system.drawing.size(273, 21);
   this.textbox1.tabindex = 0;
   this.textbox1.text = “23+56/(102-100)*((36-24)/(8-6))”;
   //
   // button1
   //
   this.button1.location = new system.drawing.point(180, 144);
   this.button1.name = “button1”;
   this.button1.size = new system.drawing.size(84, 27);
   this.button1.tabindex = 1;
   this.button1.text = “计算(&c)”;
   this.button1.click += new system.eventhandler(this.button1_click);
   //
   // textbox2
   //
   this.textbox2.location = new system.drawing.point(114, 72);
   this.textbox2.name = “textbox2”;
   this.textbox2.size = new system.drawing.size(273, 21);
   this.textbox2.tabindex = 2;
   this.textbox2.text = “”;
   //
   // label1
   //
   this.label1.autosize = true;
   this.label1.location = new system.drawing.point(48, 36);
   this.label1.name = “label1”;
   this.label1.size = new system.drawing.size(54, 17);
   this.label1.tabindex = 3;
   this.label1.text = “字符串:”;
   //
   // label2
   //
   this.label2.autosize = true;
   this.label2.location = new system.drawing.point(39, 75);
   this.label2.name = “label2”;
   this.label2.size = new system.drawing.size(66, 17);
   this.label2.tabindex = 3;
   this.label2.text = “计算结果:”;
   //
   // form1
   //
   this.autoscalebasesize = new system.drawing.size(6, 14);
   this.clientsize = new system.drawing.size(442, 221);
   this.controls.add(this.label1);
   this.controls.add(this.textbox2);
   this.controls.add(this.button1);
   this.controls.add(this.textbox1);
   this.controls.add(this.label2);
   this.name = “form1”;
   this.text = “form1”;
   this.resumelayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [stathread]
  static void main()
  {
   application.run(new form1());
  }

  private void button1_click(object sender, system.eventargs e)
  {

         textbox2.text = calculateparenthesesexpression(textbox1.text.tostring());
  }

  
  //中序转换成后序表达式再计算
  // 如:23+56/(102-100)*((36-24)/(8-6))
  // 转换成:23|56|102|100|-|/|*|36|24|-|8|6|-|/|*|+”
  //以便利用栈的方式都进行计算。
  private string  calculateparenthesesexpression(string expression)
  {
   arraylist operatorlist = new arraylist();
   string operator1;
   string expressionstring = “”;
   string operand3;
   expression = expression.replace(” “,””);
   while(expression.length > 0)
   {
    operand3 = “”;
    //取数字处理
    if(char.isnumber(expression[0]))
    {
     while(char.isnumber(expression[0]))
     {
      operand3 += expression[0].tostring() ;
      expression = expression.substring(1);
      if(expression == “”)break;

     }
     expressionstring += operand3 + “|”;
    }

    //取“c”处理
    if(expression.length >0 && expression[0].tostring() == “(“)
    {
     operatorlist.add(“(“); 
     expression = expression.substring(1);
    }

    //取“)”处理
    operand3 = “”;
    if(expression.length >0 && expression[0].tostring() == “)”)
    {
     do
     {
      
      if(operatorlist[operatorlist.count -1].tostring() != “(“)
      {
       operand3 += operatorlist[operatorlist.count -1].tostring() + “|” ;
       operatorlist.removeat(operatorlist.count – 1) ;
      }
      else
      {
       operatorlist.removeat(operatorlist.count – 1) ;
       break;
      }
      
     }while(true);
     expressionstring += operand3;
     expression = expression.substring(1);
    }

    //取运算符号处理
    operand3 = “”;
    if(expression.length >0 &&  (expression[0].tostring() == “*” || expression[0].tostring() == “/” || expression[0].tostring() == “+” || expression[0].tostring() == “-“))
    {
     operator1 = expression[0].tostring();
     if(operatorlist.count>0)
     {
       
      if(operatorlist[operatorlist.count -1].tostring() == “(” || verifyoperatorpriority(operator1,operatorlist[operatorlist.count – 1].tostring()))
       
       {
        operatorlist.add(operator1);
       }
       else 
       {
        operand3 += operatorlist[operatorlist.count – 1].tostring() + “|”;
        operatorlist.removeat(operatorlist.count – 1);
        operatorlist.add(operator1);
        expressionstring += operand3 ;
       
       }
      
     }
     else
     {
      operatorlist.add(operator1);
     }
     expression = expression.substring(1);
    }
   }

   operand3 = “”;
   while(operatorlist.count != 0)
   {
    operand3 += operatorlist[operatorlist.count -1].tostring () + “|”;
    operatorlist.removeat(operatorlist.count -1);
   } 

   expressionstring += operand3.substring(0, operand3.length -1);  ;
   

   return calculateparenthesesexpressionex(expressionstring);

  }

  // 第二步:把转换成后序表达的式子计算
  //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;
  }
 
 }
}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 字符串表达式计算C#程序设计-.NET教程,C#语言
分享到: 更多 (0)