小算盤
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool isFirstDigit = true/* 是否為第一個數字*/, isOP1 = true/* 是否為第一個運算元*/;
Int64 result = 0, op1 = 0, op2 = 0;
char op;//放置加減乘除
int d1=0;
public Form1()
{
InitializeComponent();
}
private void calc_result() //計算結果
{
if (txtOp.Text.Equals("") || txtOp1.Text.Equals("") || txtOp2.Text.Equals("")) return;
op1 = Int64.Parse(txtOp1.Text);
op2 = Int64.Parse(txtOp2.Text);
txtOp2.Text = "";
txtOp.Text = "";
switch (op)
{
case '+':
result = op1 + op2; break;
case '-':
result = op1 - op2; break;
case '*':
result = op1 * op2; break;
case '/':
result = op1 / op2; break;
}
txtResult.Text = result.ToString();
txtOp1.Text = result.ToString();
}
private void button1_Click(object sender, EventArgs e) //數字按鈕按下
{
Button b = (Button)sender;
if (isFirstDigit)
{
if (b.Text.Equals("0")) return;
else
{
isFirstDigit = false;
}
}
if (isOP1)
{
txtOp1.Text += b.Text.ToString();
d1 = 0;
}
else
{
txtOp2.Text += b.Text.ToString();
d1 = 1;
}
}
private void button11_Click(object sender, EventArgs e) //等號按鈕按下
{
if (!txtOp2.Text.Equals("0")) calc_result();
}
private void button12_Click(object sender, EventArgs e) //+-/*按鈕按下
{
if (txtOp.Text == "")
{
if (isFirstDigit) return;
Button b = (Button)sender;
op = b.Text[0];
txtOp.Text = b.Text;
if (isOP1) isOP1 = false;
isFirstDigit = true;
calc_result();
}
else
{
txtOp.Text = "";
Button b = (Button)sender;
op = b.Text[0];
txtOp.Text = b.Text;
if (isOP1) isOP1 = false;
isFirstDigit = true;
calc_result();
}
}
private void button17_Click(object sender, EventArgs e) //清除鍵
{
txtResult.Text = "";
txtOp1.Text = "";
txtOp2.Text = "";
txtOp.Text = "";
isOP1 = true;
}
private void button18_Click(object sender, EventArgs e) //記憶鍵
{
if (txtOp3.Text != "")
{
txtOp3.Text = "";
txtOp3.Text = txtResult.Text;
}
else
{
txtOp3.Text = txtResult.Text;
}
}
private void button19_Click(object sender, EventArgs e) //取出記憶鍵
{
if (txtOp1.Text == "")
{
txtOp1.Text = txtOp3.Text;
txtResult.Text = txtOp3.Text;
}
else
{
txtOp2.Text = txtOp3.Text;
txtResult.Text = txtOp3.Text;
}
}
private void button16_Click(object sender, EventArgs e) //倒退鍵
{
if (d1 == 0)
{
string newStr = txtOp1.Text.Substring(0, txtOp1.Text.Length - 1);
txtResult.Text = newStr;
txtOp1.Text = txtResult.Text;
}
else
{
string newStr = txtOp2.Text.Substring(0, txtOp2.Text.Length - 1);
txtResult.Text = newStr;
txtOp2.Text = txtResult.Text;
}
}
}
}
執行結果
測試影片