3월 12일 #연산자, #조건문

sejun-Lee·2025년 3월 12일
<region> 코드 접기 기능. 실행에는 문제없음.
            #region 플레이어 기능  // 이름 붙이기 가능
            Console.WriteLine("Hello, World!");
            Console.WriteLine("Hello, World!");
            Console.WriteLine("Hello, World!");
            Console.WriteLine("Hello, World!");
            Console.WriteLine("Hello, World!");
            #endregion	//여기까지 코드 접힘

연산자 (Operator)

  1. 프로그래밍 언어에서는 일반적인 수학 연산과 유사한 연산자들이 지원됨
  2. C#는 여러 연산자를 제공하며 기본 연산을 수행할 수 있음

산술 연산자

✅ <이진 연산자>

            Console.WriteLine(5 + 2);       // + 더하기
            Console.WriteLine(5 - 2);       // - 뺴기
            Console.WriteLine(5 * 2);       // * 곱하기
            Console.WriteLine(5 / 2);       // / 나누기 -> int의 나눗셈은 소수점 버림.
            Console.WriteLine(5f / 2f);     //  float, double 등 한쪽 만이라도 사용시 소수점 계산
            Console.WriteLine(5 % 2);       // % 나머지 연산자 -> 나누고 나눈 나머지 1

✅ <단항 연산자>

            int level = 1;
            level = +level;		 // + 단항연사자(양수) : 그대로 두기
            level = -level;		 // - 단항연산자(음수) : 값을 반전하여 바꾸기 (원래 값에 - 함)
            ++level;       		 // 전위증가연산자 : 값을 1 증가
            level++;       		 // 후위증가연산자 : 값을 1 증가
            --level;       		 // 전위감소연산자 : 값을 1 감소
            level--;       		 // 후위감소연산자 : 값을 1 감소

✅ <전위연산자와 후위연산자>

            전위연산자 : 값을 반환하기 전에 연산
            int ivalue = 0;
            Console.WriteLine(ivalue);      //output : 0
            Console.WriteLine(++ivalue);    //output : 1    먼저 더하고 반환
            Console.WriteLine(ivalue);      //output : 1
            
            후위연산자 : 값을 반환한 후에 연산
            int ivalue = 0;
            Console.WriteLine(ivalue);      //output : 0
            Console.WriteLine(ivalue++);    //output : 0    반환한 후 다음 더함
            Console.WriteLine(ivalue);      //output : 1

대입 연산자

✅ <대입연산자>

            int value = 10;     //  = 의 오른쪽의 값을 왼쪽 변수에 대입

산술 연산자

            // 1의 자리 숫자
            Console.WriteLine(59386737 % 10);

            // 10의 자리 숫자
            Console.WriteLine(59386737 / 10 % 10);

            // 100의 자리 숫자
            Console.WriteLine(59386737 / 100 % 10);

            // <복합 대입 연산자>
            // 이진 연산자(op)의 경우
            // x op = y 는 x = x op y 와 동일
            int exp = 0;
            exp += 5;         // exp = exp + 5; 와 동일


            Console.Write("캐릭터의 이름을 입력해주세요 : ");
            string name = Console.ReadLine();   //ReadLine 은 문자열만 받음.
            Console.Write("입력하신 이름 : {0}", name);
            Console.WriteLine();

            Console.Write("나이를 입력해주세요 : ");
            string age = Console.ReadLine();
            Console.WriteLine("입력하신 나이 : {0}", age);
            //문자열 string 과의 + 는 그냥 붙여서 쓰는 것
            Console.WriteLine("다음년도의 나이 : {0}", age + 1);

            //문자열 보간, $ -> 사용시 위치가 햇갈릴 위험은 없음. {}를 사용하여 변수 사용 가능
            Console.Write($"입력하신 나이는 : {age} 입니다");


            //  2/5 결과는 실수가 될 것.
            float dividedNum;
            dividedNum = 2f / 5;    //float를 쓰거나 2.0소수점을 써줘야 소수점 자리 버리지 않음.
            Console.WriteLine(dividedNum);

            float distance = 9.8f;
            int partyMember = 4;
            Console.WriteLine((int)distance / partyMember);  //형 변환 -> 소수점 버린 후 9/4
            Console.WriteLine((int)(distance / partyMember));  //형 변환 -> 9.8/4 후에 소수점 버림
            //데이터 손실에 주의하자

            Console.WriteLine(1.1f + 0.3f);
            //float로 계산시 0.00001등의 오차가 있을 수 있다. 이진수 변환 과정에서 오차 0.1 무한소수.

조건문(Conditional)

  1. 조건에 따라 실행이 달라지게 할 때 사용하는 문장

if 조건문

  1. 조건식 true, false에 따라 실행할 블록을 결정하는 조건문

✅ <if 조건문 기본 >

            int hp = 100;
            int damage;
            string input = Console.ReadLine();
            damage = int.Parse(input);

            bool alive = hp > damage;
            if (alive == false)
            {
                Console.WriteLine("죽었다!");
            }
            Console.WriteLine("끝");

--------------------------------------------------------------------------------------------------------

            int exp = 100;
            int level = 1;

            if (exp >= 100)
            {
                // 레벨업
                level++;
                Console.WriteLine("레벨업!!");
                exp -= 100;
            }

            Console.WriteLine("레벨 : {0}", level);
            Console.WriteLine("경험치 : {0}", exp);
            Console.WriteLine("끝");

--------------------------------------------------------------------------------------------------------

            // 컴퓨터 : 가위
            Console.WriteLine("가위! 바위! 보!.");
            string platerChoice = Console.ReadLine();
            if (platerChoice == "바위")
            {
                Console.ForegroundColor = ConsoleColor.Green;   // **출력 글자색 변경**
                Console.WriteLine("이겼습니다.");
                Console.ResetColor();   // **리셋으로 원복하지 않으면 계속 색깔 변경된 상태**
            }
            else if (platerChoice == "가위")
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("비겼습니다.");
                Console.ResetColor();
            }
            else if (platerChoice == "보")
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("졌습니다.");
                Console.ResetColor();
            }
            else  // 위 조건 모두 아닐 경우
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("잘못입력했습니다.");
                Console.ResetColor();
            }
            Console.WriteLine("게임 종료!");

--------------------------------------------------------------------------------------------------------

            // 100~90 : 골드 , 89~80 : 실버, 79~ : 브론즈
            int score = 92;
            if (score < 80)
            {
                Console.WriteLine("브론즈입니다!");
            }
            else if (score < 90)
            {
                Console.WriteLine("실버입니다.!");
            }
            else
            {
                Console.WriteLine("골드입니다!");
            }

--------------------------------------------------------------------------------------------------------

            const int maxItemCount = 8;
            int potionCount = 2;
            // 포션을 먹으면 인벤토리에 추가한다.
            // ->
            // 1.인벤토라가 가득 찼는지 확인해본다.
            if (potionCount >= maxItemCount)
            {
                // 1-1. 꽉 찼으면 안먹는다.
                Console.WriteLine("포션을 먹지 못합니다");
            }
            // 1-2. 꽉 차지 않았으면
            // 2.이미 포션이 있었는지 확인해본다.
            // 2-1. 이미포션이 있었으면
            else if (potionCount >= 1)
            {
                // 2-2. 포션갯수를 하나 늘린다.
                potionCount++;
                Console.WriteLine("인벤토리에 있는 포션에 갯수를 하나 늘립니다!");
            }

            // 3.포션이 없었으면
            else if (potionCount == 0)
            {
                // 3-1. 새로 포션을 얻고
                potionCount = 1;
                // 3-2. 인벤토리에 칸에 표시해준다
                Console.WriteLine("인벤토리에 포션을 하나 추가합니다!");
            }
            
--------------------------------------------------------------------------------------------------------
            
            Console.Write("잔고를 입력해주세요 : ");
            string input = Console.ReadLine();
            int gold;
            
            // string을 int.Parse(); 또는 int.TryParse(); 를 사용하여 int로 변환
            bool success = int.TryParse(input, out gold);  // bool -> 입력이 유효하다면 true, 아니면 flase
            //int.TryParse(); // 입력이 유효하면 넘어가고, 안되면 0을 출력
            //int.Parse(input); // 이상없이 잘 될거라는 전제 하에 가능

            if (success)
            {
                Console.WriteLine("입력하신 잔고 : {0}", gold);
                gold += 10000;
                Console.WriteLine("만원 입금 후 잔고 : {0}", gold);
            }
            else
            {
                Console.WriteLine("잘못된 값을 입력하셨습니다.");	// 오류 방지
            }

논리 연산자

✅ <논리 연산자>

            bool bValue;           
            bValue = !false;            // !(Not)   : 피연산자의 논리 부정을 반환
            bValue = true && false;     // &&(And)  : 두 피연산자가 모두 true 일 경우 true
            bValue = true || false;     // ||(Or)   : 두 피연산자가 모두 false 일 경우 false

            // 어몽어스 (마피아)
            // 시민 
            // 1. 모든 임무를 완료하기
            // 2. 모든 마피아를 검거하기
            
			//    1       2
            if (true || true)
            {
                Console.WriteLine("승리했습니다!");
            }

            // 게임 진행 조건
            // 1. 접속이 되어 있으면서
            // 2. 레디 상태일 때

            //    1       2
            if (true && false)
            {
                Console.WriteLine("게임이 가능합니다!");
            }

switch 조건문

  1. 조건값에 따라 실행할 시작지점을 결정하는 조건문

✅ <switch 조건문 기본>

            // 특정한 상황에서 조건을 추가 삭제하기에 좋다
            // 가독성이 매우 뛰어나다.
            char key = "w";
            switch (key)
            {
                case "w":
                case "W":
                case "ㅈ":
                    // 조이패드 위 버튼
                    Console.WriteLine("위쪽으로 이동");
                    break;

                case "s":
                case "S":
                case "ㄴ":
                    Console.WriteLine("아래로 이동");
                    break;

                case "a":
                case "A":
                case "ㅁ":
                    Console.WriteLine("왼쪽으로 이동");
                    break;

                case "d":
                case "D":
                case "ㅇ":
                    Console.WriteLine("오른쪽으로 이동");
                    break;

                default:
                    Console.WriteLine("이동하지 않음");
                    break;

            }
profile
초보 개발자

0개의 댓글