1. Rookiss 강의 - C# 기초 프로그래밍 입문(3)

이규성·2024년 6월 21일
0

TIL

목록 보기
99/106

06/21

내가 좋아하는 조건문 ㅎ... 기능이 제대로 동작하지 않을 때 냅다 조건문 떡칠로 테스트 후에 고치면 잘 됐다!

📌조건문

if문과 switch문을 알려주셨고 실습까지 진행하였다.

가위바위보!

class Program
{
    static void Main(string[] args)
    {
        Random rand = new Random();
        int aiChoice = rand.Next(0, 3);

        int choice = Convert.ToInt32(Console.ReadLine());

        switch (choice)
        {
            case 0:
                Console.WriteLine("가위 ");
                break;
            case 1:
                Console.WriteLine("rock ");
                break;
            case 2:
                Console.WriteLine("보 ");
                break;
        }

        switch (aiChoice)
        {
            case 0:
                Console.WriteLine("컴 가위 ");
                break;
            case 1:
                Console.WriteLine("ai rock ");
                break;
            case 2:
                Console.WriteLine("보 ");
                break;
        }

        if ((choice == 0 && aiChoice == 1) || 
        (choice == 1 && aiChoice == 2) || 
        (choice == 2 && aiChoice == 0))
        {
            Console.WriteLine("ai is win");
        }
        else if (choice == aiChoice)
        {
            Console.WriteLine("draw");
        }
        else
        {
            Console.WriteLine("human is win ");
        }
    }
}

📌상수와 열거형

위의 코드를 상수형 const를 사용하여 개선

class Program
{
    static void Main(string[] args)
    {
        const int SCI = 0;
        const int ROCK = 1;
        const int PAPER = 2;

        Random rand = new Random();
        int aiChoice = rand.Next(0, 3);

        int choice = Convert.ToInt32(Console.ReadLine());

        switch (choice)
        {
            case SCI:
                Console.WriteLine("가위 ");
                break;
            case ROCK:
                Console.WriteLine("rock ");
                break;
            case PAPER:
                Console.WriteLine("보 ");
                break;
        }

        switch (aiChoice)
        {
            case SCI:
                Console.WriteLine("컴 가위 ");
                break;
            case ROCK:
                Console.WriteLine("ai rock ");
                break;
            case PAPER:
                Console.WriteLine("보 ");
                break;
        }

        if ((choice == SCI && aiChoice == ROCK) || 
        (choice == ROCK && aiChoice == PAPER) || 
        (choice == PAPER && aiChoice == SCI))
        {
            Console.WriteLine("ai is win");
        }
        else if (choice == aiChoice)
        {
            Console.WriteLine("draw");
        }
        else
        {
            Console.WriteLine("human is win ");
        }
    }
}

if문에서는 변수명으로 비교해도 문제가 없지만 switch문에서는 변하지 않는 값을 case에 넣어줘야하기 때문에 변수 앞에 const를 붙여서 상수형으로 만든 뒤 사용한다.
참조:https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/const

열거형을 이용한 개선

class Program
{
    enum Choice
    {
        sci, // 0
        rock, // 1
        paper // 2
    }

    static void Main(string[] args)
    {
        Random rand = new Random();
        int aiChoice = rand.Next(0, 3);

        int choice = Convert.ToInt32(Console.ReadLine());

        switch (choice)
        {
            case (int)Choice.sci:
                Console.WriteLine("가위 ");
                break;
            case (int)Choice.rock:
                Console.WriteLine("rock ");
                break;
            case (int)Choice.paper:
                Console.WriteLine("보 ");
                break;
        }

        switch (aiChoice)
        {
            case (int)Choice.sci:
                Console.WriteLine("컴 가위 ");
                break;
            case (int)Choice.rock:
                Console.WriteLine("ai rock ");
                break;
            case (int)Choice.paper:
                Console.WriteLine("보 ");
                break;
        }

        if ((choice == (int)Choice.sci && aiChoice == (int)Choice.rock) ||
            (choice == (int)Choice.rock && aiChoice == (int)Choice.paper) ||
            (choice == (int)Choice.paper && aiChoice == (int)Choice.sci))
        {
            Console.WriteLine("ai is win");
        }
        else if (choice == aiChoice)
        {
            Console.WriteLine("draw");
        }
        else
        {
            Console.WriteLine("human is win ");
        }
    }
}

이미 사용법을 알고 있기에 별로 어렵지 않았으나 열거형은 꽤 복잡하고 사용법이 많기에 너무 간단하게 언급하고 넘어가서 아쉬웠다. 아직 초반부라 그런 것 같다.

📌함수

ref, out 키워드

함수는 보통 접근제한자 반환타입 이름 (변수) 순서로 작성이 된다. 반환타입이 없으면 void를 사용하게 된다. 변수를 그냥 작성하면 원본의 값은 건드리지 않고 복사를 이용하여 결과값이 나오게 된다. 또한 return하는 값도 1개로 강제된다.

여러가지 값을 return하거나, 원본의 값을 바꾸기 위해서 ref, out 키워드를 사용할 수 있다.

class Program
{
    static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }

    static void Main(string[] args)
    {
        int a = 1;
        int b = 2;

        Swap(ref a, ref b);

        Console.WriteLine(a);
        Console.WriteLine(b);
        // 출력값 2, 1
    }
}

대표적인 두 변수의 값을 뒤바꾸는 로직이다. void로 함수를 만들면 반환값이 없어서 출력 값이 1, 2로 바뀌지 않아야 하지만 ref 키워드를 변수 앞에 붙여주면 원본 값을 건드릴 수 있게 된다.

class Program
{
    static void Swap(int x, int y, out int result1, out int result2)
    {
        result1 = x / y;
        result2 = x % y;
    }

    static void Main(string[] args)
    {
        int a = 10;
        int b = 3;

        int result1;
        int result2;

        Swap(a, b, out result1, out result2);

        Console.WriteLine(result1);
        Console.WriteLine(result2);
        // 출력값 3, 1
    }
}

하나의 함수로 여러개의 반환값이 필요한 경우 out 키워드를 변수 앞에 붙여서 사용할 수 있다. ref와 다른 점은 키워드를 붙인 변수를 반드시 사용해야 한다는 점이다.

📌오버로딩

함수의 이름을 동일하게 매개변수는 다르게.
비슷한 기능을 하는 함수들의 가독성, 재사용성 향상을 꾀하기 위해 사용한다.

class Program
{
    static int Add(int a, int b, int c = 0, 
    float d = 1.0f, double e = 2.0)
    {

        return a + b + c;
    }

    static void Main(string[] args)
    {
        Add(1, 2, 3, 4.0f, 5.0);
        Add(1, 2, d:2.0f);
    }
}

오버로딩을 알고 있었으나 위와 같은 사용은 처음 보는 방식이라서 작성한다.

🤸🏻‍♀️Feedback

아직까지는 알고 있는 내용이 더 많아서 빠르게 넘어가고 있다. 연습 문제에서 별찍기가 나왔을 땐 너무 오랜만이라서 당황하였지만 이내 금방 떠올리고는 풀 수 있었다. (가슴을 쓸어내리며) 강의를 따라가며 맥os에 익숙해지기 위해서 맥북으로 작업을 하고 있는데 진짜 예쁘고 성능 좋은 것 빼고는 불편한 것 투성이다...

0개의 댓글