您的位置:首页 > 其它

四则运算

2015-10-05 09:59 344 查看
使用窗体之我的截图:



代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private String operation = null;

//点击等于按钮事件
private void btnEtc_Click(object sender, EventArgs e)
{
//判断文本框是否为空
if (null != txtB1.Text && txtB1.Text != "")
{
if (txtB1.Text.Equals("") || txtB1.Text.Equals(除数不能为0!") || txtB1.Text.Equals("本计算器暂未添加小数操作!"))
{
operation = null;
return;
}

if (txtB1.Text.IndexOf(".") != -1)
{
txtB1.Text = "本计算器暂未添加小数操作!";
operation = null;
return;
}
calculate(null);
}
}

//按钮0~9和运算符号点击触发事件
public void btnShu_Click(object sender, EventArgs e)
{
String txt = "";

if (null != txtB1.Text && txtB1.Text != "")
{
if (!txtB1.Text.Equals("") && !txtB1.Text.Equals("除数不能为0!") && !txtB1.Text.Equals("本计算器暂未添加小数操作!"))
{
txt = txt + txtB1.Text;
}
}

if (sender is Button)
{
Button btn = (Button)sender;
txt = txt + btn.Text;
}
if (sender == btnAdd)
{
checkOper(btnAdd.Text);
return;
}
else if (sender == btnSub)
{
checkOper(btnSub.Text);
return;
}
else if (sender == btnMul)
{
checkOper(btnMul.Text);
return;
}
else if (sender == btnDiv)
{
checkOper(btnDiv.Text);
return;
}
txtB1.Text = txt;
}

//验证运算符
private void checkOper(String t)
{
if (null != txtB1.Text && txtB1.Text != "")
{
if (operation == null)
{
txtB1.Text = txtB1.Text + t;
operation = t;
}
else
{
calculate(t);
}
}
else
{
txtB1.Text = "";
}
}

//运算方法
private void calculate(String t)
{
//获取运算符前面的值
int before = Convert.ToInt32(txtB1.Text.Substring(0, txtB1.Text.IndexOf(operation)));
//防止多次点击运算符
if (txtB1.Text.Length == txtB1.Text.IndexOf(operation) + 1)
{
return;
}
//获取运算符后面的值
int after = Convert.ToInt32(txtB1.Text.Substring(txtB1.Text.IndexOf(operation) + 1, txtB1.Text.Length - (txtB1.Text.IndexOf(operation) + 1)));

//用switch进行判断计算
switch (operation)
{
case "+":
txtB1.Text = (before + after).ToString();
break;
case "-":
txtB1.Text = (before - after).ToString();
break;
case "*":
txtB1.Text = (before * after).ToString();
break;
case "/":
if (before == 0)
{
txtB1.Text = "除数不能为0!";
}
else
{
txtB1.Text = Math.Round((decimal)before / after, 2).ToString();
}
break;
default:
break;
}
operation = t;
txtB1.Text = txtB1.Text + t;
}

private void btnClear_Click(object sender, EventArgs e)
{
txtB1.Text = "";
operation = null;
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: