사용자 입력에 따라 기본 산술 연산(+, -, *, /)을 수행하는 간단한 C# 계산기 프로그램을 만듭니다. 프로그램은 다음과 같아야 합니다:
주의!
화이팅!💕
추가 정보! 테스트 코드에서 무엇을 기대하나요?
테스트 코드는 계산기 프로그램이 특정 시나리오를 올바르게 처리하는지 확인합니다. 자세한 내용은 다음과 같습니다:
+, -, *, /+, -, *, /+, -, *, /+, -, *, 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) | 잘못된 연산 시 예외 발생으로 오류 방지 |