티스토리 뷰

간혹 숫자를 다루는 프로그램을 작성할 것이다. 이때 여러분이 사용하는 프로그래밍 언어에 따라 입력 값을 숫자로 변환해야 할 경우도 생길 것이다. 두 개의 숫자를 입력 받은 후, 두 숫자를 이용한 사칙연산 결과를 다음의 출력 예와 같이 나타내보자.

#출력 예 What is the first number? 10

What is the second number? 5

10 + 5 = 15

10 - 5 = 5

10 * 5 = 50

10 / 5 = 2

#제약 조건

  • 문자열로 입력 받도록 할 것. 이렇게 받은 문자열 값은 사칙연산을 하기 전에 숫자 값으로 변환시켜야 한다.
  • 입력 값과 출력 값 모두 숫자 변환 및 기타 프로세스에 영향을 받지 않도록 할 것
  • 한 개의 출력문만 사용하여 적당한 위치에 줄바꿈 글자를 넣을 것

#도전 과제

  • 숫자만 입력되도록 프로그램을 수정해보자. 숫자가 아닌 값이 입력된 경우 진행되면 안 된다.
  • 음수를 넣을 수 없도록 하라.
  • 계산 부분을 함수로 구현해보자. 함수에 대해서는 5장 ‘함수’에서 확인할 수 있다.
  • 앞의 프로그램을 GUI로 구현하여 숫자를 넣는 즉시 자동으로 계산 결과가 업데이트되도록 하라.



My code

static void Main(string[] args)
{
    while (true)
    {
        int iFirst = 0, iSecond = 0;
 
        First:
        Console.Write("What is the first number? ");
        string firstNum = Console.ReadLine();
 
        if (!int.TryParse(firstNum, out iFirst))
        {
            goto First;
        }
 
        if (iFirst < 0)
        {
            goto First;
        }
 
        Second:
        Console.Write("What is the second number? ");
 
        string secondNum = Console.ReadLine();
 
        if (!int.TryParse(secondNum, out iSecond))
        {
            goto Second;
        }
 
        if (iSecond < 0)
        {
            goto Second;
        }
 
        Console.WriteLine("{0} + {1} = {2}", iFirst, iSecond, Calc(iFirst,iSecond,"+"));
        Console.WriteLine("{0} - {1} = {2}", iFirst, iSecond, Calc(iFirst, iSecond, "-"));
        Console.WriteLine("{0} * {1} = {2}", iFirst, iSecond, Calc(iFirst, iSecond, "*"));
        Console.WriteLine("{0} / {1} = {2}", iFirst, iSecond, Calc(iFirst, iSecond, "/"));
    }
}
 
static int Calc(int first, int second, string alth)
{
 
    switch (alth)
    {
        case "+":
            return first + second;
        case "-":
            return first - second;
        case "*":
            return first * second;
        default:
            return first / second;
    }
}
cs


Result



댓글
글 보관함
최근에 올라온 글
최근에 달린 댓글