ในการสร้างโปรแกรมเครื่องคิดเลขในภาษา C# คุณต้องใช้เว็บฟอร์ม ภายใต้นั้นสร้างปุ่มตั้งแต่ 1-9 บวก ลบ คูณ ฯลฯ
ให้เราดูโค้ดสำหรับการบวก การลบ และการคูณ ประการแรก เราได้ประกาศตัวแปรสองตัว -
static float x, y;
ตอนนี้เราจะมาดูวิธีการตั้งรหัสสำหรับการคำนวณในแต่ละปุ่มที่คลิก:กล่องข้อความผลลัพธ์ของเราคือ tbResult เนื่องจากเราใช้ Windows Form เช่นกันเพื่อแสดงเครื่องคิดเลข -
protected void add_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '+';
tbResult.Text += y;
}
protected void sub_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '-';
tbResult.Text += y;
}
protected void mul_Click(object sender, EventArgs e) {
x = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
y = '*';
tbResult.Text += y;
} ต่อไปนี้คือรหัสปุ่มเท่ากับ -
protected void eql_Click(object sender, EventArgs e) {
z = Convert.ToInt32(tbResult.Text);
tbResult.Text = "";
if (y == '/') {
p = x / z;
tbResult.Text += p;
x = d;
} else if (y == '+') {
p = x + z;
tbResult.Text += p;
a = d;
} else if (y == '-') {
p = x - z;
tbResult.Text += p;
x = p;
} else {
p = x * z;
tbResult.Text += p;
x = p;
}
}