ตัวอย่าง Calculator ใช้ Web Forms (ASP.NET) มีปุ่ม 0-9 และตัวดำเนินการ +, -, ×, ÷
โครงสร้างหลัก
- TextBox แสดงผล (
tbResult) - ตัวแปรเก็บค่า:
x(operand แรก),y(operator),z(operand ที่สอง) - Event handlers สำหรับปุ่มต่างๆ
โค้ดสำหรับปุ่มตัวดำเนินการ
static float x, y; // x = operand1, y = operator char
protected void Add_Click(object sender, EventArgs e) {
x = Convert.ToSingle(tbResult.Text);
tbResult.Text = "";
y = '+';
}
protected void Sub_Click(object sender, EventArgs e) {
x = Convert.ToSingle(tbResult.Text);
tbResult.Text = "";
y = '-';
}
protected void Mul_Click(object sender, EventArgs e) {
x = Convert.ToSingle(tbResult.Text);
tbResult.Text = "";
y = '*';
}
protected void Div_Click(object sender, EventArgs e) {
x = Convert.ToSingle(tbResult.Text);
tbResult.Text = "";
y = '/';
}
โค้ดปุ่ม Equals (=)
protected void Eq_Click(object sender, EventArgs e) {
float z = Convert.ToSingle(tbResult.Text);
tbResult.Text = "";
float result = 0;
switch (y) {
case '+': result = x + z; break;
case '-': result = x - z; break;
case '*': result = x * z; break;
case '/': result = z != 0 ? x / z : float.NaN; break;
}
tbResult.Text = result.ToString();
x = result; // สำหรับการคำนวณต่อเนื่อง
}
หมายเหตุ: โค้ดต้นฉบับมีตัวแปรสับสน (a, d, p) ผมปรับปรุงให้ชัดเจน และเพิ่มการป้องกันหารด้วยศูนย์