C#, Windows Forms

[WinForm]계산기

박순창 2021. 7. 9. 10:14
728x90

목표)

- 계산기 제작

 

동작)

- 숫자버튼(0~9)을 눌러 숫자 추가

- 연산버튼(+,-,*,/)을 눌러 연산자 추가

- 결과버튼(=)을 눌러 연산 실행과 표시

 

동작영상)

계산기

코드)

public partial class Form1 : Form
    {
        private double value1, value2;
        private string op;
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.label1_Result.Text = "";
            value1 = value2 = 0;
            this.op = null;   // \0를 의미  
        }
        private void button_Dight_Click(object sender, EventArgs e)
        {
            Button btn;

            btn = (Button)sender;
            this.textBox_Result.Text += btn.Text;   // strcat
            this.label1_Result.Text += btn.Text;
        }

        private void button_Equal_Click(object sender, EventArgs e)
        {
            this.value2 = double.Parse(this.textBox_Result.Text);
            this.textBox_Result.Text = string.Empty;
            this.label1_Result.Text += "=";

            switch (this.op)
            {
                case "+":
                    this.textBox_Result.Text = (this.value1 + this.value2).ToString();
                    break;
                case "-":
                    this.textBox_Result.Text = (this.value1 - this.value2).ToString();
                    break;
                case "X":
                    this.textBox_Result.Text = (this.value1 * this.value2).ToString();
                    break;
                case "/":
                    this.textBox_Result.Text = (this.value1 / this.value2).ToString();
                    break;
            }
        }

        private void button_Clear_Click(object sender, EventArgs e)
        {
            value1 = value2 = 0;
            this.op = null;   // \0
            this.textBox_Result.Text = this.label1_Result.Text =  string.Empty;
        }

        private void button_BackSpace_Click(object sender, EventArgs e)
        {
            if (this.textBox_Result.Text == string.Empty)
                return;

            this.textBox_Result.Text = this.textBox_Result.Text.Substring(0, this.textBox_Result.Text.Length - 1);
            this.label1_Result.Text = this.label1_Result.Text.Substring(0, this.label1_Result.Text.Length - 1);
        }

        private void button_Op_Click(object sender, EventArgs e)
        {
            Button op;

            op = (Button)sender;
            this.op = op.Text;
            this.label1_Result.Text += op.Text;
            this.value1 = double.Parse(this.textBox_Result.Text);
            this.textBox_Result.Text = "";

        }
    }

 

 

개선사항)

1. 이전 데이터, 기록을 저장할 수 있는 함수 생성

2.  공학용 계산기 기능 추가