[SKKU DT] 22일차 -C# 연산자 정리(증감, 조건부, 할당 연산자), 조건문(If, Switch), 반복문

2023. 11. 28. 18:55SKKU DT

728x90
반응형

Version Control System

-소스 저장

-히스토리 관리

-협업

 

https://git-scm.com/book/en/v2

 

Git - Book

 

git-scm.com

Git Document

 

 

Visual Studio에서 [보기] - [Git 변경 내용]을 열면 변경 사항을 볼 수 있다.

커밋도 올릴 수 있다.

 

 


 

 

변수의 계산, 증감 연산자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArithmaticOperators : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        {
            int a = 111 + 222;
            Debug.Log($"a : {a}");

            int b = a - 100;
            Debug.Log($"b : {b}");

            int c = b * 10;
            Debug.Log($"c : {c}");

            double d = c / 6.3;
            Debug.Log($"d : {d}");

            Debug.Log($"22 / 7 = {22 / 7}({22 % 7})");
        }
        {
            int a = 10;
            Debug.Log(a++);
            Debug.Log(++a);

            Debug.Log(a--);
            Debug.Log(--a);
        }
        {
            string result = "123" + "456";
            Debug.Log(result);

            result = "Hello" + " " + "World";
            Debug.Log(result);
        }
    }
}

 

 


 

 

Null 조건부 연산자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NullConditionalOperator : MonoBehaviour
{
    void Start()
    {
        ArrayList a = null;
        a?.Add("야구");
        a?.Add("축구");
        Debug.Log($"Count : {a?.Count}");
        Debug.Log($"{a?[0]}");
        Debug.Log($"{a?[1]}");
        //a?. 뜻은 a가 null이 아닐 경우 뒤의 함수를 실행한다.
        //a가 null을 반환하므로 출력 값이 "Count : " 말고는 없다.

        a = new ArrayList(); //메모리 값이 생성되고 a가 만들어지면 null이 아니다.
        a?.Add("야구");
        a?.Add("축구");
        Debug.Log($"Count : {a?.Count}");
        Debug.Log($"{a?[0]}");
        Debug.Log($"{a?[1]}");

        Person person = new Person();
        person.Walk();
    }
}

 

 


 

 

비트 연산자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShiftOperator : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Testing <<...");

        int a = 1; //int 타입은 4바이트, 32비트로 이루어져 있다. 32칸 중에 가장 오른쪽 칸이 1이 된다.

        Debug.Log(string.Format("a : {0:D5} (0x{0:X8})", a)); //첫번째 값 0을(a를) 십진수 5자리로 표현해라, a를 8자리 16진수로 표현해라.
        Debug.Log(string.Format("a << 1 : {0:D5} (0x{0:X8})", a << 1)); //왼쪽으로 한 칸 옮겨라
        Debug.Log(string.Format("a << 2 : {0:D5} (0x{0:X8})", a << 2)); //왼쪽으로 두 칸 옮겨라
        Debug.Log(string.Format("a << 5 : {0:D5} (0x{0:X8})", a << 5)); //왼쪽으로 다섯 칸 옮겨라

        Debug.Log("Testing >> ...");

        int b = 255;

        Debug.Log(string.Format("b : {0:D5} (0x{0:X8})", b));
        Debug.Log(string.Format("b << 1 : {0:D5} (0x{0:X8})", b << 1));
        Debug.Log(string.Format("b << 2 : {0:D5} (0x{0:X8})", b << 2));
        Debug.Log(string.Format("b << 5 : {0:D5} (0x{0:X8})", b << 5));

        int c = -255;

        Debug.Log(string.Format("c : {0:D5} (0x{0:X8})", c));
        Debug.Log(string.Format("c << 1 : {0:D5} (0x{0:X8})", c << 1));
        Debug.Log(string.Format("c << 2 : {0:D5} (0x{0:X8})", c << 2));
        Debug.Log(string.Format("c << 5 : {0:D5} (0x{0:X8})", c << 5));
    }
}

 

 


 

 

할당 연산자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AssignmentOperator : MonoBehaviour
{
    void Start()
    {
        int a;
        a = 100;
        Debug.Log($"a = 100 : {a}"); //100 출력
        a += 90;
        Debug.Log($"a += 90 : {a}"); //190 출력
        a -= 80;
        Debug.Log($"a -= 80 : {a}"); //110 출력
        a *= 70;
        Debug.Log($"a *= 70 : {a}"); //7700 출력
        a /= 60;
        Debug.Log($"a /= 60 : {a}"); //128 출력
        a %= 50;
        Debug.Log($"a %= 50 : {a}"); //28 출력
        a &= 40;
        Debug.Log($"a &= 40 : {a}"); //8 출력
        a |= 30;
        Debug.Log($"a |= 30 : {a}"); //30 출력
        a ^= 20;
        Debug.Log($"a ^= 20 : {a}"); //10 출력
        a <<= 10;
        Debug.Log($"a <<= 10 : {a}"); //10240 출력
        a >>= 2;
        Debug.Log($"a =>> 2 : {a}"); //5120 출력
    }
}

 

 


 

 

조건문 버튼 누르면 출력하기

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class IfElse : MonoBehaviour
{
    //화면에 결과를 출력할 Text
    public TMP_Text text;
    //사용자에게 입력을 받을 Input Field
    public TMP_InputField inputField;

    //버튼이 클릭 되었을 때 동작할 함수
    public void ButtonClicked()
    {
        string input = inputField.text;
        int number = int.Parse(input);

        if (number < 0)
        {
            text.text = "음수";
        }
        else if (number > 1)
        {
            text.text = "양수";
        }
        else
        {
            text.text = "0";
        }

        if (number % 2 == 0)
        {
            text.text = "짝수";
        }
        else
        {
            text.text = "홀수";
        }
    }
}

 

 


 

 

**다운 받은 폰트 유니티에 사용하기

.ttf 확장자의 폰트를 Project로 가져온 후 [Create] - [TextMeshPro] - [Font Asset]

 

그리고 Project에서 [Assets] - [TextMesh Pro] - [Resources] - [TMP Settings]의 Inspector에서 [Default Font Asset]을 다운 받았던 폰트로 변경한다.

 

유니티에서도 한글 폰트를 사용할 수 있게 되었다.

 

 


 

 

Switch 문

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Switch : MonoBehaviour
{
    void Start()
    {
        string day = "월";

        switch (day)
        {
            case "일":
                Debug.Log("Sunday");
                break;
            case "월":
                Debug.Log("Monday");
                break;
            case "화":
                Debug.Log("Tuesday");
                break;
            case "수":
                Debug.Log("Wednesday");
                break;
            case "목":
                Debug.Log("Thursday");
                break;
            case "금":
                Debug.Log("Friday");
                break;
            case "토":
                Debug.Log("Saturday");
                break;
            default:
                Debug.Log($"{day}는(은) 요일이 아닙니다.");
                break;
        }
    }
}

 

 

발전된 Switch 문

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class SwitchExp : MonoBehaviour
{
    void Start()
    {
        int score = Convert.ToInt32("100");

        string line = "y";
        bool repeated = line == "y" ? true : false; //line이 y이면 true, 아니면 false

        string grade = (int)(Math.Truncate(score / 10.0) * 10) switch //Math 함수, 소수점을 절삭하고 정수형으로 보여줌
        {
            90 when repeated == true => "B+", //90점이면서 재수강이면 B+
            90 => "A", //90점이면 A
            80 => "B", //80점이면 B
            70 => "C", //70점이면 C
            60 => "D", //60점이면 D
            _ => "F" //default F
        };

        Debug.Log($"학점: {grade}");
    }
}

 

 


 

 

While 반복문, do-While 반복문

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class While : MonoBehaviour
{
    void Start()
    {
        int i = 10;

        while (i > 0)
        {
            Debug.Log($"i : {i--}");
        }

        int j = 10;
        do
        {
            Debug.Log($"j : {j--}");
        }
        while (j > 0);
    }
}

 

 

For, Foreach 반복문

{
    for(int i = 0; i < 5; i++)
    {
        Debug.Log(i);
    }
}
{
    int[] arr = new int[] { 0, 1, 2, 3, 4 };

    foreach (int i in arr)
    {
        Debug.Log(i);
    }
}

 

 


 

 

Break 문, Continue 문

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Break : MonoBehaviour
{
    void Start()
    {
        {
            while (true)
            {
                string answer = "y";

                if (answer == "y")
                {
                    break;
                }
            }
        }
        {
            for(int i = 0; i < 10; i++)
            {
                if(i % 2 == 0)
                {
                    continue;
                }
                Debug.Log($"{i} : 홀수");
            }
        }
    }
}

continue문 실행 결과 (1 : 홀수, 3 : 홀수, 5 : 홀수, 7 : 홀수, 9 : 홀수) 짝수는 넘어간다.

 

 

 


 

 

Goto 문 (안쓰는 게 좋다...)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Goto : MonoBehaviour
{
    void Start()
    {
        int input_number = Convert.ToInt32(5);

        int exit_number = 0;

        for(int i = 0; i < 2; i++)
        {
            for(int j = 0; j < 2; j++)
            {
                for(int k = 0; k < 2; k++)
                {
                    if (exit_number++ == input_number)
                        goto EXIT_FOR;

                    Debug.Log(exit_number);
                }
            }
        }

        goto EXIT_PROGRAM;

    EXIT_FOR:
        Debug.Log("Exit nested for...");
    EXIT_PROGRAM:
        Debug.Log("Exit program...");
    }
}

 

 


 

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace C06
{
    public class Calculator : MonoBehaviour
    {
        void Start()
        {
            int result = MyCalculator.Plus(3, 4);
            Debug.Log(result);

            result = MyCalculator.Minus(5, 2);
            Debug.Log(result);
        }
    }

    public class MyCalculator
    {
        public static int Plus(int a, int b)
        {
            return a + b;
        }

        public static int Minus(int a, int b)
        {
            return a - b;
        }
    }
}

**static이 있으면 클래스를 객체화 하지 않아도 사용할 수 있다.

MyCalculator myCalculator = new MyCalculator();

int result;

result = myCalculator.Plus(3, 4);
result = myCalculator.Minus(5, 2);

static을 쓰지 않으면 위와 같이 객체화 해야한다.

728x90
반응형