关于四则运算的算法的更新

原创 2004年07月24日 14:17:00

//This new version is derived from the prvious one which was changed to test the
//aquirement of the learning of the Exceptions.
//
//This program is designed for arithmetic,the operand is assumed to be double.
//
//This program can detect a lot of syntax errors,including illegal operands and illegal expression.
//Also the error of divided by zero can be detected,when a syntax error is detected,a warning message read
//"Error! illegal expression!"is displayed,and the result is set to 0.
//
//If the button1 is clicked when the textBox of expression is blank, a warning message read "Error! blank expression!"
//is displayed.
//
//It is set that some illegal characters can't be input into the expression.

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplication8
{
 /// <summary>
 /// Summary description for Form1.
 /// </summary>
  
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.TextBox txtExp;
  private System.Windows.Forms.Label expLbl;
  private System.Windows.Forms.Label rstLbl;
  private System.Windows.Forms.TextBox txtRst;
  private System.Windows.Forms.Button button2;
  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
  }

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.button1 = new System.Windows.Forms.Button();
   this.txtExp = new System.Windows.Forms.TextBox();
   this.expLbl = new System.Windows.Forms.Label();
   this.rstLbl = new System.Windows.Forms.Label();
   this.txtRst = new System.Windows.Forms.TextBox();
   this.button2 = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // button1
   //
   this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
   this.button1.Location = new System.Drawing.Point(112, 336);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(72, 24);
   this.button1.TabIndex = 0;
   this.button1.Text = "Calculate";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // txtExp
   //
   this.txtExp.Location = new System.Drawing.Point(168, 64);
   this.txtExp.Name = "txtExp";
   this.txtExp.Size = new System.Drawing.Size(296, 21);
   this.txtExp.TabIndex = 1;
   this.txtExp.Text = "";
   this.txtExp.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtExp_KeyPress);
   //
   // expLbl
   //
   this.expLbl.Location = new System.Drawing.Point(56, 64);
   this.expLbl.Name = "expLbl";
   this.expLbl.Size = new System.Drawing.Size(92, 23);
   this.expLbl.TabIndex = 2;
   this.expLbl.Text = "expression";
   //
   // rstLbl
   //
   this.rstLbl.Location = new System.Drawing.Point(56, 136);
   this.rstLbl.Name = "rstLbl";
   this.rstLbl.Size = new System.Drawing.Size(124, 23);
   this.rstLbl.TabIndex = 3;
   this.rstLbl.Text = "result";
   //
   // txtRst
   //
   this.txtRst.Location = new System.Drawing.Point(168, 136);
   this.txtRst.Name = "txtRst";
   this.txtRst.ReadOnly = true;
   this.txtRst.Size = new System.Drawing.Size(128, 21);
   this.txtRst.TabIndex = 4;
   this.txtRst.Text = "";
   //
   // button2
   //
   this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
   this.button2.Location = new System.Drawing.Point(360, 336);
   this.button2.Name = "button2";
   this.button2.TabIndex = 5;
   this.button2.Text = "Clear";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(592, 429);
   this.Controls.Add(this.button2);
   this.Controls.Add(this.txtRst);
   this.Controls.Add(this.rstLbl);
   this.Controls.Add(this.expLbl);
   this.Controls.Add(this.txtExp);
   this.Controls.Add(this.button1);
   this.Name = "Form1";
   this.Text = "ExpressionEvaluation_lihui";
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

 

  class Stack
  {
   protected ArrayList vectors;
   protected int length;
   protected object element;
 
   public Stack()
   {
    vectors = new ArrayList(20);
    length = 0;
   }

   public virtual int getLength()
   {
    length = vectors.Count;
    return length;
   }

           
   public virtual void put(object dbl)
   {
    vectors.Add(dbl);
    length = length+1;
   }
   

   public virtual void pop()
   {
    vectors.RemoveAt(length-1);
    length = length-1;
   }

            /*
   public virtual object getTop()
   {
    element = (object)vectors[length-1];
    return element;
   }
   */

   public virtual void traverse()
   {
   }

   public virtual void clear()
   {
    for(int i=length-1;i>=0;i--)
    {
     vectors.RemoveAt(i);
    }
   }
  }


  class OpndStack:Stack
  {
   public OpndStack():base()
   {
    vectors = new ArrayList(20);
    length = 0;
   }

   public override void put(object dbl)
   {
    vectors.Add(dbl);
    length = length+1;
   }

   public double getTop()
   {
    element = (object)vectors[length-1];
    return (double)element;
   }
  }

  class OptrStack:Stack
  {
   public OptrStack():base()
   {
    vectors = new ArrayList(20);
    length = 0;
   }

   public override void put(object dbl)
   {
    vectors.Add(dbl);
    length = length+1;
   }

   public char getTop()
   {
    element = (object)vectors[length-1];
    return (char)element;
   }
  }

 

  class Compare
  {
   private char[] operators=new char[7];
   private int index;

   public Compare()
   {
    index=0;
    operators[0]='+';
    operators[1]='-';
    operators[2]='*';
    operators[3]='/';
    operators[4]='(';
    operators[5]=')';
    operators[6]='#';
   }

   public bool contains(char e)
   {
    bool found=false;
    int i;
    for(i=0;i<7&&found==false;i++)
     if(operators[i]==e)
      found=true;
    if(found==false)
     return false;
    else
     return true;
   }

   public int getIndex(char e)
   {
    int i;
    bool found=false;
    for(i=0;i<7&&found==false;i++)
     if(operators[i]==e)
     {
    
      index=i;
      found=true;
     }

    return index;
   }
  }


  
  class IllegalExpressionException:ApplicationException
  {
   public IllegalExpressionException(string message):base(message)
   {
   }
   public IllegalExpressionException(string message,Exception innerException):base(message,innerException)
   {
   }
  }
       

  class DividedByZeroException:ApplicationException
  {
   public DividedByZeroException(string message):base(message)
   {
   }
   public DividedByZeroException(string message,Exception innerException):base(message,innerException)
   {
   }
  }
  


    
  class ExpProcs
   {
 
    private char[,] p = new char[7,7];
    private OptrStack optr;
    private OpndStack opnd;
    private Compare com;
 
  
    public ExpProcs()
    {
     p[0,0]='>';p[0,1]='>';p[0,2]='<';p[0,3]='<';p[0,4]='<';p[0,5]='>';p[0,6]='>';
     p[1,0]='<';p[1,1]='<';p[1,2]='<';p[1,3]='<';p[1,4]='<';p[1,5]='>';p[1,6]='>';
     p[2,0]='>';p[2,1]='>';p[2,2]='>';p[2,3]='>';p[2,4]='<';p[2,5]='>';p[2,6]='>';
     p[3,0]='>';p[3,1]='>';p[3,2]='>';p[3,3]='>';p[3,4]='<';p[3,5]='>';p[3,6]='>';
     p[4,0]='<';p[4,1]='<';p[4,2]='<';p[4,3]='<';p[4,4]='<';p[4,5]='=';p[4,6]='0';
     p[5,0]='>';p[5,1]='>';p[5,2]='>';p[5,3]='>';p[5,4]='0';p[5,5]='>';p[5,6]='>';
     p[6,0]='<';p[6,1]='<';p[6,2]='<';p[6,3]='<';p[6,4]='<';p[6,5]='0';p[6,6]='=';
  
     optr=new OptrStack();
     opnd=new OpndStack();
     com=new Compare();
    }

          
       public double execute(string exp)
    {
  
     int i=0;
     bool errorFound=false;    
     double numAfterDot=1;
     double d=0;
     string expression;
     expression=exp;
     expression+='#';
 
     optr.clear();
     opnd.clear();
    
     optr.put('#');
    
     try
     {
      while(expression[i]!='#'||optr.getTop()!='#')
      {
     
      
       if(Char.IsNumber(expression[i])||expression[i]=='.')
       {    
        while(Char.IsNumber(expression[i])||expression[i]=='.')
        {
         if(expression[i]!='.')
         {
          d=d*10+(int)expression[i]-48;
          i++;
         }
         else    
         {     
          i++;
          while(Char.IsNumber(expression[i]))
          {
           numAfterDot*=10;     
           d=d+((int)expression[i]-48)/numAfterDot;
           i++;
          }
          if(expression[i]=='.')
          {
           throw new IllegalExpressionException("Error! illegal expression!");
          }
         } 
        }
        numAfterDot=1;
        opnd.put(d);
        d=0;          
       }
               
       
       if(!Char.IsNumber(expression[i])&&expression[i]!='.')
       {
        if(i>0&&expression[i-1]!='.'&&!Char.IsNumber(expression[i-1]))
         if(expression[i]!='('&&expression[i-1]!=')')
         {
          throw new IllegalExpressionException("Error! illegal expression!");
         }
        if(errorFound==false)
        {
         char optr_=optr.getTop();
         int x=com.getIndex(optr_);
         int y=com.getIndex(expression[i]);
         switch(p[x,y])
         {
          case '<':
           optr.put(expression[i]);
           //Console.WriteLine("operator stack");
           optr.traverse();
           i++;
           break;
          case '=':
           optr.pop();
           //Console.WriteLine("operator stack");
           optr.traverse();
           i++;
           break;
          case '>':
           char op=optr.getTop();
           optr.pop();
           //Console.WriteLine("operator stack");
           optr.traverse();     
     
           double b=opnd.getTop();
           opnd.pop();
           double a=opnd.getTop();
           opnd.pop();

           //Console.WriteLine("operand stack");
           //opnd.traverse();     
     
          switch(com.getIndex(op))
          {
           case 0:opnd.put(a+b);break;
           case 1:opnd.put(a-b);break;
           case 2:opnd.put(a*b);break;
           case 3:
            if(b!=0)
             opnd.put(a/b);
            else
            {
             throw new DividedByZeroException("Error! divided by zero!");
            }
            break;     
          }
           break;
          default :
          {
           throw new IllegalExpressionException("Error! illegal expression!");
          }
           //break;
         }
        }
       }
       
      }
                        return opnd.getTop();
     }
    
   
     catch(IllegalExpressionException e)
     {    
      MessageBox.Show(e.Message,"Form1",MessageBoxButtons.OK);
      return 0;
     }
   
     catch(DividedByZeroException e)
     {
      MessageBox.Show(e.Message,"Form1",MessageBoxButtons.OK);
      return 0;
     }
 
    }
   }

  private void button1_Click(object sender, System.EventArgs e)
  {
   double result;
   ExpProcs expprocs = new ExpProcs();
   string expression=txtExp.Text;
   if(expression!="")
   {
    if(expression.Equals("."))
     MessageBox.Show("Error! illegal expression!","Form1",MessageBoxButtons.OK);
    else
    {
     result=expprocs.execute(expression);
     txtRst.Text=result.ToString();    
    }
   }
   else
   {
    MessageBox.Show("Error! blank expression!","Form1",MessageBoxButtons.OK);
   }     
  }

  private void button2_Click(object sender, System.EventArgs e)
  {
   txtExp.Text="";
   txtRst.Text="";

  }

  private void txtExp_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
  {
   double result;
   ExpProcs expprocs = new ExpProcs();
   string expression=txtExp.Text;

   
   if(e.KeyChar==(char)13)
   {
    if(expression!="")
    {
     if(expression.Equals("."))
      MessageBox.Show("Error! illegal expression!","Form1",MessageBoxButtons.OK);
     else
     {
      result=expprocs.execute(expression);
      txtRst.Text=result.ToString();    
     }
    }
    else
    {
     MessageBox.Show("Error! blank expression!","Form1",MessageBoxButtons.OK);
    } 
   }
   else      
    if(!Char.IsNumber(e.KeyChar)&&e.KeyChar!=(char)8&&e.KeyChar!='+'&&e.KeyChar!='-'&&    
    e.KeyChar!='*'&&e.KeyChar!='/'&&e.KeyChar!='('&&e.KeyChar!=')'&&e.KeyChar!='#'&&e.KeyChar!='.')
    e.Handled=true;
  }

 }
}

C# 多网卡 Server Listen

时间: 2004/5/20作者: Robert参考: MSDN电邮: zsc771120@yahoo.com.cn关键词: TcpListener IPEndPoint IPAddress IPAdd...
  • zzzsssccc
  • zzzsssccc
  • 2004-05-23 16:26:00
  • 1639

用后缀表达式计算四则运算算法

1*2+3*4, 这个对应的中缀表达式就是[1,*,2,+,3,*,4], 需要转换成后缀表达式[1,2,*,3,4,*,+], 才能进一步计算得到结果.1.得到后缀表达式需要准备两个容器, 符号栈 ...
  • chuchus
  • chuchus
  • 2017-04-24 11:15:02
  • 876

表达式(四则运算)计算的算法

表达式(四则运算)计算的算法戏剧前奏——基本知识点通常我们所看到的算术表达式,运算符总是在两个操作数中间(除),如(A+B)*C,这样的表达式叫做中缀表达式。这种表达式不同的运算符优先级不同,而且通常...
  • luoweifu
  • luoweifu
  • 2013-08-29 00:24:39
  • 15496

编译原理---四则运算表达式的计算简单实现

编译原理---四则运算表达式的计算简单实现
  • u010251278
  • u010251278
  • 2016-09-05 19:17:50
  • 3827

PAT乙级 有理数四则运算(20)

此题只要注意一下除法时候的负数情况就ok了,剩下的就完全模拟题意.此题中复习了一下辗转相除法,求最大公约数. #include "iostream" #include "string.h" #inc...
  • djd1234567
  • djd1234567
  • 2015-12-22 17:52:59
  • 1170

ACM学习历程25——高精度四则运算

在ACM的题目中会涉及到一些四则运算,需要注意的是这里参与四则运算的数据的数据类型并非整型。事实上,尽管整型可以分配4个字节的存储空间,但是它所能表示的数据范围仍然是有限的,所以在比赛上遇到加法等一些...
  • u010480899
  • u010480899
  • 2016-09-01 21:39:32
  • 608

四则运算 (数据结构)

 顺便把一个四则运算的代码贴出来了,上学期大一写的,核心算法跟我写的重言式我中的virtualCreateTree函数类似,这就不啰嗦一遍了, 代码如下: (可能有bug)/**//*********...
  • littlehedgehog
  • littlehedgehog
  • 2007-11-13 18:39:00
  • 1977

数据结构(四)java模拟计算器四则运算算法

用java模拟解决计算器四则运算算法问题
  • shuaicihai
  • shuaicihai
  • 2017-02-03 16:16:28
  • 2304

java计算的字符串四则运算

  • 2013年11月09日 11:42
  • 7KB
  • 下载

带括号的四则优先级运算的算法详细源码实现

欢迎各位来到我的博客,如果觉得小弟写得还行就收藏吧! 各位可能是刚开始学单片机,或许是51单片机、stm32单片机,也可能是刚开始学各种编程语言,想完成一个小小的功能齐全的计算器程序。如果只是为了完...
  • kangkanglhb88008
  • kangkanglhb88008
  • 2017-08-21 18:52:26
  • 437
收藏助手
不良信息举报
您举报文章:关于四则运算的算法的更新
举报原因:
原因补充:

(最多只允许输入30个字)