偶写的一个对四则运算的表达式进行处理的小程序.

原创 2004年07月16日 11:05:00

//可以查错,包括很多语法错误和除零错误.可以对表达式进行追加修改.

//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 OpndStack
  {
   private ArrayList vectors;
   private int length;
   private double element;
 
   public OpndStack()
   {
    vectors = new ArrayList(20);
    length = 0;
   }

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

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

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

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

   public void traverse()
   {
    for(int i=0;i<length;i++)
    {
     //Console.WriteLine((double)vectors[i]);
    }
   }

   public void clear()
   {
    for(int i=length-1;i>=0;i--)
    {
     vectors.RemoveAt(i);
    }
    //Console.WriteLine("all elements been removed");
   }
  }


  class OptrStack
  {
   private ArrayList vectors;
   private int length;
   private char element;
 
   public OptrStack()
   {
    vectors = new ArrayList(20);
    length = 0;
   }

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

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

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

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

   public void traverse()
   {
    for(int i=0;i<length;i++)
    {
     //Console.WriteLine((char)vectors[i]);
    }
   }

   public void clear()
   {
    for(int i=length-1;i>=0;i--)
    {
     vectors.RemoveAt(i);
    }
    //Console.WriteLine("all elements been removed");
   }
  }


  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 ExpProcs
  {
 
   private char[,] p = new char[7,7];
   private OptrStack optr;
   private OpndStack opnd;
   private Compare com;
 
 
 
   public ExpProcs()
   {
    //char[,] p = new char[7,7];
    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 e)
   {
  
    int i=0;
    bool errorFound=false;    
    double numAfterDot=1;
    double d=0;
    string expression;
    expression=e;
    //expression=Form1.txtExp.Text;
    expression+='#';
 
    optr.clear();
    opnd.clear();
    
    optr.put('#');
    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]=='.')
        {
         MessageBox.Show("Error! illegal expression!","Form1",MessageBoxButtons.OK);
         errorFound=true;
        }
       }
       if(errorFound==true)
        break;
      }
      numAfterDot=1;
      opnd.put(d);
      d=0;          
     }
     if(errorFound==true)
      break;
     if(!Char.IsNumber(expression[i])&&expression[i]!='.'&&errorFound==false)
     {
      if(i>0&&expression[i-1]!='.'&&!Char.IsNumber(expression[i-1]))
       if(expression[i]!='('&&expression[i-1]!=')')
       {
        MessageBox.Show("Error! illegal expression!","Form1",MessageBoxButtons.OK);
        errorFound=true;
       }
      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
          {
           //exit if divided by zero
           //Console.WriteLine("Error! divided by zero! 2");
           MessageBox.Show("Error! divided by zero!","Form1",MessageBoxButtons.OK);
           errorFound=true;
          }
          break;     
        }
         //Console.WriteLine("operand stack");
         //opnd.traverse();
         break;
        default :
        {
         //exit if illegal expression is found
         //Console.WriteLine("Error! illegal expression!");
         MessageBox.Show("Error! illegal expression!","Form1",MessageBoxButtons.OK);
         errorFound=true;
        }
         break;
       }
      }
     }
     if(errorFound==true)
      break;     
    }
    //Console.WriteLine(opnd.getTop());
    if(errorFound==false)
    {    
     return opnd.getTop();
    }
    else 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;
  }

 }
}

小程序(十六)简单四则运算

问题描述: 输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值 注: 3.1、表达式只含 +, -, *, / 四则运算符,不含括号 3.2、表达式数值只包含个位整数(0-9),且不会...
  • lvyuan30276
  • lvyuan30276
  • 2013-08-18 16:10:31
  • 1642

java运算四则运算表达式的程序

  • 2014年07月10日 18:23
  • 14KB
  • 下载

栈的应用--递归与四则运算表达式求值

递归,是一个直接调用自己或通过一系列的调用语句间接的调用自己的函数。以斐波那契数列为例,对比其非递归和递归函数代码的区别,来让读者深刻了解递归的工作流程。四则运算表达式求值,是利用栈来完成四则运算,首...
  • dengpei187
  • dengpei187
  • 2016-07-11 09:57:14
  • 1069

四则运算表达式求值程序(C语言版)

废话不说,见代码。 《Compute.h》头文件 #include   #include   #include   /*以下为本程序涉及到的函数的声明*/ int CheckS...
  • zhouzxi
  • zhouzxi
  • 2012-08-22 20:59:35
  • 5408

用栈实现四则运算表达式(c++)

水平有限,花了两个小时实现了用栈进行基本的四则运算,只针对整数的运算。(即使两个整数相除也将得到整数)思路:将输入的中缀表达式用栈转化为后缀表达式,再根据后缀表达式用栈实现运算。中缀表达式:运算符位于...
  • scuisdccch
  • scuisdccch
  • 2015-09-29 09:55:04
  • 3172

Perl四则运算

####################################### #just use for practice #####################################...
  • zhanglintc
  • zhanglintc
  • 2013-07-13 20:13:51
  • 856

C语言实现表达式求值,支持+、-、*、/四则运算,并且支持多级括号,自定义了栈的操作。

#include #include #define N 50        //定义接收字符串大小 typedef struct _node_ {     int num_ch;     //...
  • niha1993825jian
  • niha1993825jian
  • 2014-10-30 12:59:54
  • 2779

四则混合运算表达式分析程序的原理及其实现

意义: 四则混合运算表达式可以看作一定语言中的表达式分析及求值,虽然它很小,却是一个语法分析的很好的例子!一、目标:可以对输入的四则混合运算表达式进行分析,并求出其结果。程序须支持:整数及小数运算、支...
  • oohacker
  • oohacker
  • 2007-09-26 09:55:00
  • 2282

四则运算(带括号)的小程序

看了数据结构与算法这本书,用刚学的栈写了一个能实现简单四则运算的小程序 主要是处理括号的问题 大概思路: 中缀表达式-》前缀表达式-》计算#include #include #include #...
  • amy260231120
  • amy260231120
  • 2016-03-09 21:03:27
  • 427

四则运算小程序

import java.applet.Applet;import java.applet.*;import java.awt.*;import java.awt.event.*;public clas...
  • wuhongze
  • wuhongze
  • 2005-01-09 13:30:00
  • 1117
收藏助手
不良信息举报
您举报文章:偶写的一个对四则运算的表达式进行处理的小程序.
举报原因:
原因补充:

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