본문 바로가기
개발하는 '정'/C# (.NET)

[C# .NET] 윈도우폼 계산기 예제 : 3. 추가 기능 구현

by 주앤정_블로그 2019. 7. 9.

[ C# .NET ] 윈도우 폼 계산기 예제

C# 닷넷 개인 공부를 위한 예제로, 정확하지 않거나 효율적이지 않을 수 있음★

현재 구현된 이미지

※ 예외 처리할 목록 
 1. 최초 출력 숫자가 0인 경우 (완료) 
 2. 계산 버튼 두번 클릭 시 (완료) 
 3. 변수의 크기 
 4. 숫자 -> 계산 -> 숫자 -> enter  (완료)
 5. 0 나누기 (완료) 
 6. 숫자 맨 앞자리가 0인 경우나 계산버튼을 연속으로 클릭 시 ProcessBox에 알맞게 출력하기 
 7. equal 버튼(=) 클릭 후 바로 계산버튼 클릭 시

 

※ 추가 기능 구현할 목록 
 1. 키보드 입력 
 2. 기본 계산 외 추가 계산 기능 (Clear, 소숫점, 지우기 ...)


<전체 코드>

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 WindowsFormsApp1
{
    public partial class form1 : Form
    {
        public form1()
        {
            InitializeComponent();
        }

        public double resultVal = 0; 
        public bool isNewNum = true; 
        public double num = 0;
        public string recentCal = "+";
        public string equalClickYn = "N";

        public void NumBtn_Click (object sender, EventArgs e)
        {
            if (recentCal == "=")
            {
                resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
                ResultBox.Text = "0"; ProcessBox.Text = "0";
            } //if end

            Button btnNum = sender as Button;
            num = double.Parse(btnNum.Text);

            if (isNewNum)
            {
                ResultBox.Text = num.ToString(); 
                isNewNum = false;
            }
            else if (ResultBox.Text == "0")
            {
                ResultBox.Text = num.ToString();
            }
            else 
            {
                ResultBox.Text += num.ToString(); 
            } //if end

            ProcessBox.Text += num.ToString(); 

        } //NumBtn_Click() end

        private void BtnCal_Click(object sender, EventArgs e)
        {
            Button btnCal = (Button)sender;

            if (!isNewNum) 
            {
                num = double.Parse(ResultBox.Text); 
                switch (recentCal)
                {
                    case "+":
                        resultVal = resultVal + num; 
                        break;
                    case "-":
                        resultVal = resultVal - num; 
                        break;
                    case "*":
                        resultVal = resultVal * num; 
                        break;
                    case "/":
                    /*
                        if (num == 0) {
                            ResultBox.Text = "0으로 나눌 수 없습니다"; ProcessBox.Text = "0으로 나눌 수 없습니다";
                            resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
                            ResultBox.Text = "0"; ProcessBox.Text = "0"; 
                            return;
                        } //if end
                    */
                        resultVal = resultVal / num; 
                        break;
                } //switch end
                
                ResultBox.Text = resultVal.ToString(); 
            } //if end

            recentCal = btnCal.Text;

            if (btnCal.Text == "=")
            {
                ProcessBox.Text = ResultBox.Text;
                resultVal = 0; isNewNum = true; num = 0; 
            } else
            { 
                ProcessBox.Text += recentCal;
            } //if end

            isNewNum = true; 

        } //BtnCal_Click end

        private void BtnClear_Click(object sender, EventArgs e)
        {
            resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
            ResultBox.Text = "0"; ProcessBox.Text = "0"; 
        } //BtnClear_Click end

        private void BtnDot_Click(object sender, EventArgs e)
        {
            if (!ResultBox.Text.Contains("."))
            {
                ResultBox.Text += ".";
                ProcessBox.Text += ".";
            }
        } //BtnDot_Click end

        private void BtnRemove_Click(object sender, EventArgs e)
        {
            if(ResultBox.Text != "0" && recentCal != "=" && ResultBox.Text.Length > 0) 
            {
                ResultBox.Text = ResultBox.Text.Substring(0, ResultBox.Text.Length - 1);
                ProcessBox.Text = ProcessBox.Text.Substring(0, ProcessBox.Text.Length - 1);
            }
        } //BtnRemove_Click end
    }
}

<코드 분석>

1. 숫자 버튼 클릭 이벤트

추가 내용 : if (recentCal == "=") {...}

 - 계산 완료 버튼 ("=") 클릭 후 숫자 버튼 입력 시 변수 및 출력 박스 초기화.

        public void NumBtn_Click (object sender, EventArgs e)
        {
            if (recentCal == "=")
            {
                resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
                ResultBox.Text = "0"; ProcessBox.Text = "0";
            } //"=" 버튼 클릭 후 새로운 계산 시 초기화

            Button btnNum = sender as Button;
            num = double.Parse(btnNum.Text); 

            if (isNewNum)
            {
                ResultBox.Text = num.ToString(); 
                isNewNum = false;
            }
            else if (ResultBox.Text == "0")
            {
                ResultBox.Text = num.ToString(); 
            }
            else 
            {
                ResultBox.Text += num.ToString();
            }

            ProcessBox.Text += num.ToString();

        } //NumBtn_Click() end

2. 숫자 버튼 클릭 이벤트

추가 내용 : if (btnCal.Text == "=") {...}

 - 계산 완료 버튼 ("=") 클릭 후 연산 버튼 입력 시 계산 완료 값에 추가 계산 처리.

        private void BtnCal_Click(object sender, EventArgs e)
        {
            Button btnCal = (Button)sender;

            if (!isNewNum)
            {
                num = double.Parse(ResultBox.Text);
                switch (recentCal)
                {
                    case "+":
                        resultVal = resultVal + num; 
                        break;
                    case "-":
                        resultVal = resultVal - num; 
                        break;
                    case "*":
                        resultVal = resultVal * num; 
                        break;
                    case "/":
                    /*
                        if (num == 0) {
                            ResultBox.Text = "0으로 나눌 수 없습니다"; ProcessBox.Text = "0으로 나눌 수 없습니다";
                            resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
                            ResultBox.Text = "0"; ProcessBox.Text = "0"; 
                            return;
                        }
                    */
                        resultVal = resultVal / num; 
                        break;
                }
                
                ResultBox.Text = resultVal.ToString(); 
            }

            recentCal = btnCal.Text;

            if (btnCal.Text == "=")
            {
                ProcessBox.Text = ResultBox.Text;
                resultVal = 0; isNewNum = true; num = 0; 
            } else
            { 
                ProcessBox.Text += recentCal;
            }

            isNewNum = true; 

        }

3. 추가 기능

 (1) 초기화 버튼 클릭 이벤트

    모든 변수와 출력 박스를 초기화한다.

        private void BtnClear_Click(object sender, EventArgs e)
        {
            resultVal = 0; isNewNum = true; num = 0; recentCal = "+";
            ResultBox.Text = "0"; ProcessBox.Text = "0"; 
        }

 (2) 소수점 버튼 클릭 이벤트

    출력된 값에 소수점을 붙인다.

        private void BtnDot_Click(object sender, EventArgs e)
        {
            if (!ResultBox.Text.Contains("."))
            {
                ResultBox.Text += ".";
                ProcessBox.Text += ".";
            }
        }

 (3) 지우기 버튼 클릭 이벤트

    출력된 값의 가장 마지막 문자를 지운다.

    출력 박스의 값이 없거나 0일 때, 혹은 계산 완료 버튼을 클릭한 후 클릭하는 것이 아닐 때에 처리한다.

        private void BtnRemove_Click(object sender, EventArgs e)
        {
            if(ResultBox.Text.Length > 0 && ResultBox.Text != "0" && recentCal != "=" ) 
            {
                ResultBox.Text = ResultBox.Text.Substring(0, ResultBox.Text.Length - 1);
                ProcessBox.Text = ProcessBox.Text.Substring(0, ProcessBox.Text.Length - 1);
            }
        }

<문제점>

 1. 입력 및 계산된 값이 너무 클 경우 출력이나 계산의 오류가 있을 수 있음.

 2. 0으로 나누기 시 오류 메세지가 출력되지 않고 0으로 고정됨.

 3. 숫자 맨 앞자리가 0인 경우나 연산 버튼을 연속으로 클릭 시 ProcessBox에 알맞게 출력되지 않음.

 4. equal 버튼(=) 클릭 후 바로 연산 버튼 클릭 시 연산이 안 됨.

반응형

댓글