[C#] 윈도우폼 계산기 만들기(~ing)

2024. 1. 5. 23:37[C#]/[C# 윈폼] 혼자해보는 계산기 만들기

1. UI 완성

  • 더 이쁘게 할 수 있으면 수정할 계획이다.

 

 

2. 로직 구현

  • 현재 2일동안 초기화(C), 숫자 지우기, 사칙연산, 등호, 역수, 음/양수 전환, 제곱, 제곱근 소수점, CE, % 기능까지 완료했다.
  • 내일은 수식 표시 기능과 자릿수(구현했었는데 예외처리땜에 다시 해야된다.) , 예외처리 안된 것 있으면 꼼꼼하게 살펴볼 계획이다.

다 완성되면 로직 공유 하겠습니다!

 

 

3. 마우스로 입력하는 부분은 완성해서 공유!

using System.Xml.Linq;

namespace HelloCsharpwin
{

    /*enum = 열거형 데이터 타입 -> 선언을 하고 사용할 수 있다.
    public enum Season {Spring, Summer, Fall, Winter};
    Season currentSeason = Season.Spring;
    */

    public enum Operators {Nothing, Add, Sub, Multi, Div}

    public partial class Calculator : Form
    {
        public double Result = 0;
        public bool isNewNum = true;
        public Operators Opt = Operators.Nothing;

        public Calculator()
        {
            InitializeComponent();
        }

        //숫자 버튼 클릭 이벤트
        private void NumButton_Click(object sender, EventArgs e)
        {
            Button numButton = (Button)sender;
            SetNum(numButton.Text);
        }

        //숫자 입력 처리 메소드
        public void SetNum(string num)
        {
            System.Diagnostics.Debug.WriteLine(isNewNum);

            if (isNewNum) //첫 번째 숫자이면 값을 넣어주고 아닐 경우에는 숫자 뒤에 입력한 숫자를 더해준다.(예를 들면 1 입력 시 첫 번째 숫자면 1이지만 두 번째 숫자부터 11처럼 뒤에 이어지는 형식)
            {
                NumScreen.Text = num;
                isNewNum = false;
            }
            else if(NumScreen.Text == "0")
            {
                NumScreen.Text = num;
            }
            else
            {
                NumScreen.Text += num;
            }
        }

        //사칙 연산 처리
        private void OptBtn_Click(object sender, EventArgs e)
        {
            double num = double.Parse(NumScreen.Text);

            if (Opt != Operators.Nothing && !isNewNum)
            {
                if (Opt == Operators.Add)
                    Result += num;
                else if (Opt == Operators.Sub)
                    Result -= num;
                else if (Opt == Operators.Multi)
                    Result *= num;
                else if (Opt == Operators.Div && num != 0)
                    Result /= num;
            }
            else
            {
                Result = num;
            }

            NumScreen.Text = Result.ToString();
            isNewNum = true;

            Button optButton = (Button)sender;
            System.Diagnostics.Debug.WriteLine(optButton.Text);

            Console.WriteLine(optButton.Text);

            if (optButton.Text == "+")
                Opt = Operators.Add;
            else if (optButton.Text == "-")
                Opt = Operators.Sub;
            else if (optButton.Text == "x" || optButton.Text == "*")
                Opt = Operators.Multi;
            else if (optButton.Text == "÷")
                Opt = Operators.Div;
            else
                Opt = Operators.Nothing;
                equalsBtn.Focus();

        }

        //Clear(초기화)
        private void ClearBtn_Click(object sender, EventArgs e)
        {
            Result = 0;
            Opt = Operators.Nothing;
            isNewNum = true;
            NumScreen.Text = Result.ToString();
            
        }

        //Back(숫자 지움 처리)
        //예외처리 : 글자 길이가 1보다 작으면 0으로 변경
        private void backBtn_Click(object sender, EventArgs e)
        {
            if (NumScreen.Text.Length > 1)
                NumScreen.Text = NumScreen.Text.Substring(0, NumScreen.Text.Length - 1);
            else
                NumScreen.Text = "0";

        }

        // 음수/양수 변환 처리
        private void switchPM_Click(object sender, EventArgs e)
        {
            if (double.TryParse(NumScreen.Text, out double currentNumber))
            {
                currentNumber *= -1;
                NumScreen.Text = currentNumber.ToString();
                Result = currentNumber; // 연산 결과인 Result도 부호 변경
            }
            else
            {
                NumScreen.Text = "0";
            }
        }

        //역수 처리
        private void OneOverXBtn_Click(object sender, EventArgs e)
        {
            if (!isNewNum)
            {
                double inputNumber = Double.Parse(NumScreen.Text);
                double inverse = 1.0 / inputNumber;
                NumScreen.Text = inverse.ToString();
                isNewNum = true;
            }
        }


        // 소수점 처리
        private void dotBtn_Click(object sender, EventArgs e)
        {
            if (NumScreen.Text.Contains("."))
                return;
            else
                NumScreen.Text += ".";
        }

        //제곱 처리
        private void SqrBtn_Click(object sender, EventArgs e)
        {
            double num = double.Parse(NumScreen.Text);
            double result = num * num;
            NumScreen.Text = result.ToString();
            Result = result;

        }

        //제곱근 계산
        private void rootBtn_Click(object sender, EventArgs e)
        {
            double num = double.Parse(NumScreen.Text);
            double result = Math.Sqrt(num); // 제곱근 계산
            NumScreen.Text = result.ToString();
            Result = result;

        }

        // % (퍼센트) 연산
        private void PercentBtn_Click(object sender, EventArgs e)
        {
            if (!isNewNum)
            {
                double num = double.Parse(NumScreen.Text);
                double percent = num / 100.0;
                double result = Result + (Result * percent); // 이전 결과에 퍼센트를 더함
                NumScreen.Text = result.ToString();
                isNewNum = true;
            }
        }

        // CE(현재 입력된 숫자 삭제)
        private void CEBtn_Click(object sender, EventArgs e)
        {
            NumScreen.Text = "0";
            isNewNum = true;
        }

    }
}
반응형