Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình máy tính cơ bản (Basic calculator) bằng C#

Để tạo chương trình máy tính trong C#, bạn cần sử dụng Web Forms. Dưới đó tạo các nút từ 1-9, cộng, trừ, nhân, v.v.

Hãy xem mã cho cộng, trừ, nhân. Đầu tiên, chúng ta khai báo hai biến:

static float x, y;

Bây giờ, chúng ta sẽ xem cách đặt mã tính toán trên sự kiện click nút riêng lẻ: Ô kết quả là tbResult vì chúng ta cũng dùng Windows Form để hiển thị máy tính:

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; 
}

Dưới đây là mã nút bằng:

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; 
    } 
}