개발자 승학

C# 계산기 만들기(.NET) 본문

it/C#(.NET)

C# 계산기 만들기(.NET)

유승학 2018. 5. 28. 01:13

안녕하세요~~


이번 포스팅에는 C#(.NET)으로 만드는 간단한 계산기 입니다.


안드로이드 스튜디오로 계산기를 만들어 보았는데요 C#으로도 만들어보았습니다.


안드로이드와 같이 윈도우 기본 제공 계산기를 본따서 만들었습니다.


밑에 사진을 볼게요.



[기본 계산기]



[C#계산기]



우선 하나 하나를 버튼으로 만들었습니다.

C#이기에 당연 버튼클릭 이벤트를 해주어야 겠죠?


'여기에는 수 저장'은 밑에 빨간색 박스이구요

'여기에는 현재 수 저장'은 노란색 박스 부분입니다.




전체 코드를 보겠습니다.


주석 처리를 해두었지만 맨 밑에 간단하게 설명을 참고하시면 더 이해하기 쉬울거라 생각합니다.


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 계산기

{

    public partial class Form1 : Form

    {

        string operand; // 피연산자1 저장

        string operand2; // 피연산자2 저장


        bool operand_check = false; // 피연산자1과 피연산자2중 무엇을 사용할지 확인

                                    // 연산자 즉, 더하기 ~ 나머지 버튼을 누르기 전에는 operand에 저장 누른 후에는 operand2에 값 저장

                                    // 이해완료햇쥬?

                                    // 첫 값은 무조건 operand에 저장해야 하므로 false로 설정 (개발자 마음대로~)


        double result; // 결과값


        int my_operator; // 무슨 연산자인지 확인하는 int형 flag

                         // 더하기 = 1 , 빼기 = 2 , 곱하기 = 3 , 나누기 = 4 , 나머지 = 5

                         // Constants로 상수 정의

        public const int ADD = 1;

        public const int SUB = 2;

        public const int MUL = 3;

        public const int DIV = 4;

        public const int REMAIN = 5;


        public Form1()

        {

            InitializeComponent();

            label1.Text = "여기에는 수 저장";

            label2.Text = "여기에는 현재 수 저장";

        }


        private void Btn_1_Click(object sender, EventArgs e)

        {

            if (operand_check == false)   // 연산자 누른 후 인지 아닌지 확인 후 operand에 값저장

            {

                operand += "1";          // 연산자를 누르기 전, operand에 값저장

                label2.Text = operand;

            }

            else

            {

                operand2 += "1";        // 연사자를 누른 후, operand2에 값저장

                label2.Text = operand2;

            }

        }


        private void Btn_2_Click(object sender, EventArgs e)

        {

            if (operand_check == false)   

            {

                operand += "2";          

                label2.Text = operand;

            }

            else

            {

                operand2 += "2";       

                label2.Text = operand2;

            }

        }


        private void Btn_3_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "3";

                label2.Text = operand;

            }

            else

            {

                operand2 += "3";

                label2.Text = operand2;

            }

        }


        private void Btn_4_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "4";

                label2.Text = operand;

            }

            else

            {

                operand2 += "4";

                label2.Text = operand2;

            }

        }


        private void Btn_5_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "5";

                label2.Text = operand;

            }

            else

            {

                operand2 += "5";

                label2.Text = operand2;

            }

        }


        private void Btn_6_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "6";

                label2.Text = operand;

            }

            else

            {

                operand2 += "6";

                label2.Text = operand2;

            }

        }


        private void Btn_7_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "7";

                label2.Text = operand;

            }

            else

            {

                operand2 += "7";

                label2.Text = operand2;

            }

        }


        private void Btn_8_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "8";

                label2.Text = operand;

            }

            else

            {

                operand2 += "8";

                label2.Text = operand2;

            }

        }


        private void Btn_9_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "9";

                label2.Text = operand;

            }

            else

            {

                operand2 += "9";

                label2.Text = operand2;

            }

        }


        private void Btn_0_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += "0";

                label2.Text = operand;

            }

            else

            {

                operand2 += "0";

                label2.Text = operand2;

            }

        }


        private void Btn_dot_Click(object sender, EventArgs e)

        {

            if (operand_check == false)

            {

                operand += ".";

                label2.Text = operand;

            }

            else

            {

                operand2 += ".";

                label2.Text = operand2;

            }

        }


        //더하기 버튼

        private void Btn_add_Click(object sender, EventArgs e)

        {

            my_operator = 1; 

            label1.Text = operand + " + "; // label1은 기록을 저장합니다

            label2.Text = "";              // label2는 현재 입력한 값을 저장합니다.

            operand_check = true;

        }


        //빼기 버튼

        private void Btn_sub_Click(object sender, EventArgs e)

        {

            my_operator = 2; 

            label1.Text = operand + " - ";

            label2.Text = "";

            operand_check = true;

        }


        //곱하기 버튼

        private void Btn_mul_Click(object sender, EventArgs e)

        {

            my_operator = 3;

            label1.Text = operand + " x ";  

            label2.Text = "";

            operand_check = true;

        }


        //나누기 버튼

        private void Btn_div_Click(object sender, EventArgs e)

        {

            my_operator = 4;

            label1.Text = operand + " / ";

            label2.Text = "";

            operand_check = true;

        }


        //나머지 버튼

        private void Btn_remain_Click(object sender, EventArgs e)

        {

            my_operator = 5;

            label1.Text = operand + " % ";

            label2.Text = "";

            operand_check = true;

        }


        //결과 버튼

        private void Btn_result_Click(object sender, EventArgs e)

        {

            double num_operand = System.Convert.ToDouble(operand);

            double num_operand2 = System.Convert.ToDouble(operand2);

            

            switch(my_operator)

            {

                case ADD:

                    result = num_operand + num_operand2;

                    MessageBox.Show("" + result);

                    break;


                case SUB:

                    result = num_operand - num_operand2;

                    MessageBox.Show("" + result);

                    break;


                case MUL:

                    result = num_operand * num_operand2;

                    MessageBox.Show("" + result);

                    break;


                case DIV:

                    result = num_operand / num_operand2;

                    MessageBox.Show("" + result);

                    break;


                case REMAIN:

                    result = num_operand % num_operand2;

                    MessageBox.Show("" + result);

                    break;

            }


            Reset();

        }

        

        // 전체 항목을 클리어

        private void Btn_clear_Click(object sender, EventArgs e)

        {

            Reset();

        }


        private void Btn_delete_Click(object sender, EventArgs e)

        {

            if(operand_check == false)

            {

                operand = operand.Substring(0, operand.Length - 1);

                label2.Text = operand;

            }

            else

            {

                operand2 = operand2.Substring(0, operand2.Length - 1);

                label2.Text = operand2;

            }

        }


        public void Reset()

        {

            label1.Text = "";

            label2.Text = "";

            operand = "";

            operand2 = "";

            operand_check = false;

        }


        private void Btn_pm_Click(object sender, EventArgs e)

        {

            double temp;

            if (operand_check == false)

            {

                // 양수이면 음수로

                if (System.Convert.ToDouble(operand) >= 0)

                {

                    temp = System.Convert.ToDouble(operand) * -1;

                    operand = temp.ToString();

                }

                // 음수이면 양수로

                else

                {

                    temp = System.Convert.ToDouble(operand) * -1;

                    operand = temp.ToString();

                }

                label2.Text = operand;

            }

            // 위 if문의 if~else처럼 굳이 조건을 나누지 않고 밑에 else에서 바로 * -1을 해줘도 똑같습니다.

            // 이해를 위한 설명!

            else

            {

                temp = System.Convert.ToDouble(operand) * -1;

                operand = temp.ToString();

                label2.Text = operand2;

            }           

        }

    }

}



주석 처리를 해두었습니다. 모르시는 부분은 코드의 주석 부분을 확인해주세요.


먼저 피연산자1과 피연산자2에 대한 값을 저장하기 위해 string 변수를 두 개 선언합니다.

피연산자1은 위 사진에서 빨간색 박스구요 피연산자2는 노란색 박스에요!


연산(+,-,*,/,%)버튼에는 operand_check라는 bool변수를 true로 주었습니다.

false와 true는 개발자 마음대로 설정하시면 됩니다.


피연산자1의 값을 먼저 저장하기 위해서는 false로 

피연산자1의 값이 저장되어 피연산자2의 값을 저장하기위해 true로 설정했습니다.

이해하시쥬?


그다음 연산버튼들에 대한 상수입니다.

const로 ADD = 1 , SUB = 2 , .. , REMAIN = 5로 주었고


=(결과) 버튼에서 switch문으로 어떤 연산을 해야하는지 확인합니다.

switch대신에 if ~ else 구조로도 가능하지만

이러한 조건식은 switch가 훨씬 보기 좋습니다.


안드로이드 스튜디오로 계산기를 만들어보고 c#으로 만들어본거라 수월하게 만들었네요.


도움이 되셨다면 하트랑 댓글달아주시면 고마워요.

궁금하신점은 댓글달아주세요.

'it > C#(.NET)' 카테고리의 다른 글

C# 크롬사용하기!(cefsharp)  (7) 2018.05.26
Comments