조건부 기반 계산기 만들기

Shy·2025년 3월 12일

C#

목록 보기
14/27

문제

사용자 입력에 따라 기본 산술 연산(+, -, *, /)을 수행하는 간단한 C# 계산기 프로그램을 만듭니다. 프로그램은 다음과 같아야 합니다:

  1. 사용자에게 두 개의 숫자를 입력하라는 메시지를 표시합니다.
  2. 사용자에게 산술 연산(더하기, 빼기, 곱하기, 나누기)을 선택하라는 메시지를 표시합니다.
  3. 조건문을 사용하여 선택한 연산을 수행합니다.
  4. 연산 결과를 콘솔에 인쇄합니다.
  5. 특정 메시지와 함께 0으로 나누기를 처리합니다.

주의!

  • 프로그램은 연산 결과를 올바르게 처리하고 표시할 뿐만 아니라 잘못된 연산 및 0으로 나누기를 처리해야 합니다.

화이팅!💕

추가 정보! 테스트 코드에서 무엇을 기대하나요?

테스트 코드는 계산기 프로그램이 특정 시나리오를 올바르게 처리하는지 확인합니다. 자세한 내용은 다음과 같습니다:

  1. 덧셈 테스트:
    • 인풋: 5, 3, +
    • 예상 아웃풋:
      • Enter the first number:
      • Enter the second number:
      • Choose an operation: +, -, *, /
      • Result: 8
  2. 0으로 나누기 테스트:
    • 인풋: 5, 0, /
    • 예상 아웃풋:
      • Enter the first number:
      • Enter the second number:
      • Choose an operation: +, -, *, /
      • Error: Division by zero is not allowed.
  3. Invalid Operation Test:
    • 인풋: 5, 3, %
    • 예상 아웃풋:
      • Enter the first number:
      • Enter the second number:
      • Choose an operation: +, -, *, /
      • Invalid operation. Please choose +, -, *, or /.

프로그램이 주어진 입력에 대해 이러한 정확한 출력을 생성해야 테스트를 통과할 수 있습니다.

내가 짠 코드

using System;

namespace Coding.Exercise
{
    public class Exercise
    {
        public void SimpleCalculator()
        {
            int answer = 0;
            bool flag = false;

            Console.WriteLine("Enter the first number:");
            int num1;
            while (!int.TryParse(Console.ReadLine(), out num1))
            {
                Console.WriteLine("Invalid input. Please enter a valid number:");
            }

            Console.WriteLine("Enter the second number:");
            int num2;
            while (!int.TryParse(Console.ReadLine(), out num2))
            {
                Console.WriteLine("Invalid input. Please enter a valid number:");
            }

            Console.WriteLine("Choose an operation: +, -, *, /");
            string oper = Console.ReadLine();

            switch (oper)
            {
                case "+":
                    answer = num1 + num2;
                    flag = true;
                    break;
                case "-":
                    answer = num1 - num2;
                    flag = true;
                    break;
                case "*":
                    answer = num1 * num2;
                    flag = true;
                    break;
                case "/":
                    if (num2 == 0)
                    {
                        Console.WriteLine("Error: Division by zero is not allowed.");
                    }
                    else
                    {
                        answer = num1 / num2;
                        flag = true;
                    }
                    break;
                default:
                    Console.WriteLine("Invalid operation. Please choose +, -, *, or /.");
                    break;
            }

            if (flag)
            {
                Console.WriteLine($"Result: {answer}");
            }
        }
    }
}

해답

using System; // Importing the System namespace
 
namespace Coding.Exercise // Defining the Coding.Exercise namespace
{
    public class Exercise // Defining the Exercise class
    {
        public void SimpleCalculator() // Method for a simple calculator
        {
            // Prompt the user to enter the first number
            Console.WriteLine("Enter the first number:");
            // Read the user input, convert it to a double, and store it in num1
            double num1 = Convert.ToDouble(Console.ReadLine());
 
            // Prompt the user to enter the second number
            Console.WriteLine("Enter the second number:");
            // Read the user input, convert it to a double, and store it in num2
            double num2 = Convert.ToDouble(Console.ReadLine());
 
            // Prompt the user to choose an operation
            Console.WriteLine("Choose an operation: +, -, *, /");
            // Read the user input and store it in the operation variable
            string operation = Console.ReadLine();
 
            double result; // Declare a variable to store the result
 
            // Check if the operation is addition
            if (operation == "+")
            {
                result = num1 + num2; // Perform addition
                // Display the result
                Console.WriteLine($"Result: {result}");
            }
            // Check if the operation is subtraction
            else if (operation == "-")
            {
                result = num1 - num2; // Perform subtraction
                // Display the result
                Console.WriteLine($"Result: {result}");
            }
            // Check if the operation is multiplication
            else if (operation == "*")
            {
                result = num1 * num2; // Perform multiplication
                // Display the result
                Console.WriteLine($"Result: {result}");
            }
            // Check if the operation is division
            else if (operation == "/")
            {
                // Check if the second number is not zero to avoid division by zero
                if (num2 != 0)
                {
                    result = num1 / num2; // Perform division
                    // Display the result
                    Console.WriteLine($"Result: {result}");
                }
                else
                {
                    // Display an error message for division by zero
                    Console.WriteLine("Error: Division by zero is not allowed.");
                }
            }
            else
            {
                // Display an error message for an invalid operation
                Console.WriteLine("Invalid operation. Please choose +, -, *, or /.");
            }
        }
    }
}

지피티

using System;

namespace Coding.Exercise
{
    public class Exercise
    {
        public void SimpleCalculator()
        {
            int num1 = GetValidNumber("Enter the first number:");
            int num2 = GetValidNumber("Enter the second number:");
            
            Console.WriteLine("Choose an operation: +, -, *, /");
            string oper = Console.ReadLine();

            int result = PerformCalculation(num1, num2, oper);
            Console.WriteLine($"Result: {result}");
        }

        private int GetValidNumber(string prompt)
        {
            int number;
            while (true)
            {
                Console.WriteLine(prompt);
                if (int.TryParse(Console.ReadLine(), out number))
                    return number;

                Console.WriteLine("Invalid input. Please enter a valid number.");
            }
        }

        private int PerformCalculation(int num1, int num2, string oper)
        {
            return oper switch
            {
                "+" => num1 + num2,
                "-" => num1 - num2,
                "*" => num1 * num2,
                "/" => num2 == 0 ? throw new DivideByZeroException("Error: Division by zero is not allowed.") : num1 / num2,
                _ => throw new ArgumentException("Invalid operation. Please choose +, -, *, or /.")
            };
        }
    }
}
변경 사항설명
입력 검증 분리 (GetValidNumber())숫자 입력을 받을 때 while 루프를 중복해서 사용하지 않도록 재사용 가능한 메서드로 분리
계산 로직 분리 (PerformCalculation())switch 문을 C# 8.0+의 switch 표현식으로 변환하여 간결하게 작성
예외 처리 (DivideByZeroException, ArgumentException)잘못된 연산 시 예외 발생으로 오류 방지
profile
신입사원...

0개의 댓글