C#编写简单计算器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Calc
{
class Calc
{
private string expression;
public Calc()
{
expression = "0";
}
public Calc(string exp)
{
expression = exp;
}
public string Expression
{
set
{
Expression = value;
}
get
{
return (expression);
}
}
/// <summary>
/// 四则运算
/// </summary>
/// <returns>返回结果</returns>
public double EvaluateExpression()
{
try
{
string myExp = expression + "="; //表达式。。
Stack<char> optr = new Stack<char>(myExp.Length); //存放操作符栈。。
Stack<double> opnd = new Stack<double>(myExp.Length); //存放操作数栈。。
optr.Push('=');
int index = 0; //字符索引。。
char c = myExp.ToCharArray()[index++]; //读取每一个字符。。
bool isFloat = false; //是否为小数。。
bool isNum = false; //是否为数字。。
int floatBit = 0; //小数数位。。
double num1, num2;
while ((c != '=') || (optr.Peek() != '='))
{
if ((c >= '0') && (c <= '9'))
{
if (isNum)
{
if (isFloat)
{
floatBit++;
opnd.Push(opnd.Pop() + ((int)c - 48.0) / Math.Pow(10, floatBit));
}
else
{
opnd.Push(opnd.Pop() * 10 + (int)c - 48);
}
}
else
{
opnd.Push((int)c - 48);
isNum = true;
}
c = myExp.ToCharArray()[index++];
}
else
{
if ((c == '.') && (isNum))
{
isFloat = true;
floatBit = 0;
c = myExp.ToCharArray()[index++];
}
else
{
isNum = false;
isFloat = false;
switch (Precede(optr.Peek(), c))
{
case '<':
optr.Push(c);
c = myExp.ToCharArray()[index++];
break;
case '=':
optr.Pop();
c = myExp.ToCharArray()[index++];
break;
case '>':
num2 = opnd.Pop();
num1 = opnd.Pop();
opnd.Push(Operate(num1, optr.Pop(), num2));
break;
default:
break;
}
}
}
}
return opnd.Pop();
}
catch(Exception)
{
throw new Exception("表达式不合法");
}
}
//判断优先级。。
private char Precede(char optr1, char optr2)
{
//定义一个比较结果(用二维数组存下来)。。
char[,] optrTable =
{
{ '>', '>', '<', '<', '<', '>', '>' },
{ '>', '>', '<', '<', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '<', '<', '<', '<', '<', '=', '?' },
{ '>', '>', '>', '>', '?', '>', '>' },
{ '<', '<', '<', '<', '<', '?', '=' }
};
int x = 0, y = 0;//申明存符号转化后的整数。。
//定义一个符号数组。。
char[] optrs = { '+', '-', '*', '/', '(', ')', '=' };
for (int i = 0; i < optrs.Length; ++i)
{
if (optr1 == optrs[i])
x = i;
if (optr2 == optrs[i])
y = i;
}
if (optrTable[x, y] == '?')
{
throw new Exception("表达式不合法");
}
else
{
return optrTable[x, y];
}
}
//计算两值,得出相应结果。。
private double Operate(double a, char optr, double b)
{
double result = default(double);
switch (optr)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b < Math.Pow(10, 0.000001))
{
throw new Exception("除数为0");
}
result = a / b;
break;
default:
break;
}
return result;
}
}
}
我写了一个Calc类。。能够进行包括括号在内的简单的四则运算,。。
成员变量expression为算术表达式,string类型。。
方法EvaluateExpression(),计算结果,用double返回。。
使用的时候可以这样。。
Calc myCalc = new Calc(“3+4*5”);
label1.Text = "计算结果为:" + myCalc.Expression;
给个范例:
private void button1_Click(object sender, EventArgs e)
{
Calc myCalc = new Calc(textBox1.Text);
label1.Text = "= " + myCalc.Expression;
try
{
label1.Text = "= " + myCalc.EvaluateExpression();
}
catch(Exception)
{
label1.Text = "= " + "不合法";
}
}
运行结果如下。。
不知道是否符合您的要求。。
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace jisuan
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
/// <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.textBox2 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(24, 72);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 0;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(312, 72);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 21);
this.textBox2.TabIndex = 1;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(448, 72);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(88, 21);
this.textBox3.TabIndex = 2;
//
// comboBox1
//
this.comboBox1.Items.AddRange(new object[] {
"+",
"-",
"*",
"/"});
this.comboBox1.Location = new System.Drawing.Point(152, 72);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 20);
this.comboBox1.TabIndex = 3;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(64, 184);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(104, 32);
this.button1.TabIndex = 4;
this.button1.Text = "计算";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(216, 192);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 5;
this.button2.Text = "清除";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(376, 192);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 6;
this.button3.Text = "退出";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(656, 366);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public double jia(double a,double b)
{
return a+b;
}
public double jian(double a,double b)
{
return a-b;
}
public double cheng(double a,double b)
{
return a*b;
}
public double chu(double a,double b)
{
return a/b;
}
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
}
private void button1_Click(object sender, System.EventArgs e)
{
string i=this.comboBox1.SelectedItem.ToString();
switch(i)
{
case "+":this.textBox3.Text=this.jia(double.Parse(this.textBox1.Text),double.Parse(this.textBox2.Text)).ToString();
break;
case "-":this.textBox3.Text=this.jian(double.Parse(this.textBox1.Text),double.Parse(this.textBox2.Text)).ToString();
break;
case "*":this.textBox3.Text=this.cheng(double.Parse(this.textBox1.Text),double.Parse(this.textBox2.Text)).ToString();
break;
case"/" :this.textBox3.Text=this.chu(double.Parse(this.textBox1.Text),double.Parse(this.textBox2.Text)).ToString();
break;
}
}
private void button2_Click(object sender, System.EventArgs e)
{
this.textBox1.Text=null;
this.textBox2.Text=null;
this.textBox3.Text = null;
}
private void button3_Click(object sender, EventArgs e)
{
//this.Hide();
Application.Exit();
//this.Close();
}
}
}
namespace jisuanqi
{
public partial class Form1 : Form
{
public double num1;//声明变量一
public double num2;//声明变量二
public bool YS = true;//判断是否有运算(即是否按过等号)
public string fh;//声明符号变量
public double result = 0;//结果值赋值变量
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//0到9的代码
private void button1_Click(object sender, EventArgs e)
{
if (YS)//如果有运算,即按过等号之后:textBox1清空!
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "1";
}
private void button2_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "2";
}
private void button3_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "3";
}
private void button4_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "4";
}
private void button5_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "5";
}
private void button6_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "6";
}
private void button7_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "7";
}
private void button8_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "8";
}
private void button9_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "9";
}
private void button11_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += "0";
}
private void button10_Click(object sender, EventArgs e)
{
if (YS)
{
textBox1.Text = "";
YS = false;
}
textBox1.Text += ".";
}
//清零
private void button17_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
//符号的代码
private void button13_Click(object sender, EventArgs e)
{
fh = "+";
double num1 = double.Parse(textBox1.Text); //给变量一赋值
textBox1.Text = "";
}
//等号代码
private void button18_Click(object sender, EventArgs e)
{
double num2 = double.Parse(this.textBox1.Text); //给变量二赋值
//判断是何种运算
switch (fh)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0)
{
MessageBox.Show("0不能做除数");
return;
}
result = num1 / num2;
break;
default:
break;
}
textBox1.Text = result.ToString();
YS = true; //按等号之后讲YS赋为true,则表明有运算!
}
private void button14_Click(object sender, EventArgs e)
{
fh = "-";
double num1 = double.Parse(textBox1.Text);
this.textBox1.Text = "";
}
private void button15_Click(object sender, EventArgs e)
{
fh = "*";
double num1 = double.Parse(textBox1.Text);
this.textBox1.Text = "";
}
private void button16_Click(object sender, EventArgs e)
{
fh = "/";
double num1 = double.Parse(textBox1.Text);
this.textBox1.Text = "";
}
}
}