02週作業 進階小算盤
1.程式碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
bool isFirstDigit = true, isOP1 = true, isOP2 = true;
double result = 0, op1 = 0, op2 = 0;
char op;
int d1 = 1;
public Form1()
{
InitializeComponent();
}
private void calc_result()
{
if (txtOp.Text.Equals("") || txtOp1.Text.Equals("") || txtOp2.Text.Equals("")) return;
op1 = double.Parse(txtOp1.Text);
op2 = double.Parse(txtOp2.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 btnEqual_Click(object sender, EventArgs e)
{
if (txtOp.Text.Equals("") || txtOp1.Text.Equals("") || txtOp2.Text.Equals("")) return;
if (!txtOp2.Text.Equals("0")) calc_result(); txtOp2.Text = ""; isOP2 = true;
txtRecord.Text = ""; d1 = 0;
}
private void btnNums_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();
txtRecord.Text += b.Text.ToString();
isOP2 = true;
}
else
{
txtOp2.Text += b.Text.ToString();
txtRecord.Text += b.Text.ToString();
isOP2 = false;
}
}
private void btnOperator_Click(object sender, EventArgs e)
{
isFirstDigit = false;
calc_result();
if (txtOp1.Text != "") txtRecord.Text = txtOp1.Text;
if (isFirstDigit) return;
Button b = (Button)sender;
op = b.Text[0];
txtRecord.Text += op;
txtOp.Text = b.Text;
if (isOP1) isOP1 = false;
isFirstDigit = true;
isOP2 = false;
txtOp2.Text = "";
}
private void Clear_Click(object sender, EventArgs e)
{
isFirstDigit = true;
isOP1 = true;
result = 0; op1 = 0; op2 = 0; op = ' ';
txtResult.Text = "0"; txtOp.Text = ""; txtRecord.Text = "";
txtOp1.Text = ""; txtOp2.Text = ""; txtOp3.Text = "";
}
private void M_Click(object sender, EventArgs e)
{
if (isOP2 == true) txtOp3.Text = txtOp1.Text;
else txtOp3.Text = txtOp2.Text;
}
private void R_Click(object sender, EventArgs e)
{
if (txtOp3.Text != "") txtOp2.Text = txtOp3.Text;
}
private void Back_bt(object sender, EventArgs e)
{
string ch;
if (d1 != 0)
{
if (txtRecord.Text.Length > 0)
{
ch = txtRecord.Text.Substring(0, txtRecord.Text.Length - 1);
txtRecord.Text = ch;
}
}
else
{
if (txtOp2.Text == "")
{
if (txtResult.Text.Length > 0)
{
ch = txtResult.Text.Substring(0, txtResult.Text.Length - 1);
txtResult.Text = ch;
}
}
else
{
ch = txtRecord.Text.Substring(0, txtRecord.Text.Length - 1);
txtRecord.Text = ch;
}
}
if (isOP2 == true)
{
ch = txtOp1.Text;
ch = ch.Substring(0, ch.Length - 1);
txtOp1.Text = ch;
}
if (isOP2 == false)
{
ch = txtOp2.Text;
ch = ch.Substring(0, ch.Length - 1);
txtOp2.Text = ch;
}
}
}
}
2.流程圖
3.程式結果
4.執行過程影片