프로그래밍 언어 - C#(2) 연산자와 조건문

이형눈이이상해
이형눈이이상해
∙∙조회 2

1. 저번 시간 리뷰

1.1. 상수 관련 사항

  • 일단 상수는 현 단계에서보다 유니티에 들어가고 나서 많이 쓰일 수 있음.
  • 그래서 변수와 자료형 쪽에 무게를 실어서 보는 것이 좋음.

1.2. 1에 2를 50번 곱했을 때 터진다?

  • 비트를 미루다가 0만 남게 되는데 음수 값이 뜬 것이 키 포인트였다.
  • 정수가 대입이 되었을 때, 2를 총 50번 연산 수행해 대입된 값이 지속적으로 연산하다가 2의 30제곱에서 음수가 발생 후, 0이 출력되는 현상이 발생한다.

<feat. int가 터진다>

  • 2를 연산했을 때, int는 4 byte, 32 bit이며 이진수상 32개의 0, 1을 표현 가능했을 것.
  • 시계상 1~12까지의 숫자가 적혀있고 시계를 돌리는 방법을 생각해보면 이 원리가 이해갈 수 있다.
  • CPU 상의 법칙은 int에 대해 그렇게 생각할 수 있다는 것.
  • 앞 쪽 첫 비트는 양수인지 음수인지에 대해 판별하는 쪽이다.
  • 보수(완전 대비되는 수)에 의해 올라가는데 33 bit의 경우 표시될 수 있겠으나 32 bit를 초과하는 값만 가져가다보니 맨 앞 1 bit를 버리게 되는데 이것을 정수 오버플로우라고 한다.
  • 시계처럼 순환하는 결과인 셈.
  • 그래서 음수 발생 이후에 0만 발생하게 되는 것.
  • 음수는 최소값이 절대값 상에서 1이 많은 이유가 양수일 때는 0부터 하기 떄문.
  • 2의 배수로 진행 시, 왼쪽으로 계속 shift 발생.
  • 31번째에서 첫번째 부호 비트까지 범람하게 되어 예상치 못한 값이 출력.
  • 결국 32번째에 정수 오버플로우로 인해 33 bit쪽이 없게 되어 0이 표시됨.
  • 계속 0이 표시되는 것은 오버플로우가 되어 이미 0이기 때문에 0에 곱해봐야 0이기 때문이다.

1.3. 키워드

  • 시프팅
  • 2의 보수
  • 맨 앞자리 비트
  • 이진법
  • 8진법 : 3자리씩 끊어 읽기
  • 16진법 : 4자리씩 끊어 읽기
  • 벡터
  • 서적 : 한 권으로 배우는 게임 프로그래밍(라이트)
  • 서적 : 이득우의 게임 수학(헤비)
  • 다음 발표 주제 : 실수형의 표현 방법. 왜 실수끼리 더했는데 같다는 조건식을 발생시켰을 때 예상값과 다른 결과가 나올까?

2. 연산자

2.1. 개요

  • 계산하는 것이 다이다.
  • 사칙연산과 나머지 연산자인 %가 포함되는 정도.
  • 예를 들어 지급 골드가 있고 파티원의 수대로 나눈다고 했을 때를 생각해보면 사칙 연산이 적용되고 있다.

2.2. 대입연산자

  • = 기호 하나.
  • 순서는 오른쪽 값이 왼쪽으로 들어간다.
  • 이것을 산술 연산자와 융합해서 좀 더 편리하게 할 수 있음.
  • +=, -=, *=, /= 뭐 이런식.

2.3. 비교 연산자

  • 두 값에 대해 같은지 큰지 작은지 판별하는 용도.
  • 비교식은 맞다 아니다 진위 여부만 있다. 그러니까 참 거짓으로 bool 형태라는 것.

2.4. 논리 연산자

  • 살펴볼만한 사항은 And, or, not이다.
  • not은 입력값으로 0이 들어간다면 출력값이 1이 나온다. 즉, 반전 출력.
  • and는 둘 다 true일 경우만 true, false가 하나라도 있으면 false.
  • or은 하나라도 true면 true로 출력.
  • 그래서 and는 &&, or은 ||, not은 !이다.
  • 판단이 종합적으로 많을 때 사용.

2.5. 증감 연산자

  • 횟수 카운팅 등을 증감 연산자를 통해 바로 쓸 수 있게 설정함.
  • ++, -- 이런 형식.
  • 이것은 변수가 있을 때, 변수 앞과 뒤에 붙일 수 있다.
  • 이 2가지 방법이 과정과 결과적으로 다르다.

2.6. 삼항 연산자(1)

  • 조건문을 좀 더 간결히 표현할 때 사용한다.
  • 조건문을 익힌 다음, 볼 것이다.

2.7. 예제

  • 간단한 산술 연산자 연습은 다음과 같다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;
		
		// 이 상태에서 더한 값을 해볼 것이다. 변수에 담아서 해볼 것. 
		int sumResult = a + b; // 대입 연산자를 통해 sumResult에 a+b를 대입한다는 것.
		int minusResult = a - b;
		int multiplyResult = a * b;
		// 단, 0으로 나누거나 나머지 값은 존재하지 않는다. 
		int divideResult = a / b; // 나눈 값만 표시, 나머지 값은 버린다. 
		int remainResult = a % b;
		
		Console.WriteLine(sumResult);
		Console.WriteLine(minusResult);
		Console.WriteLine(multiplyResult);
		Console.WriteLine(divideResult);
		Console.WriteLine(remainResult);
	}
}
  • 하지만 원하는 것이 소수점까지 나오는 상황이라면?
  • 이럴 때, 형변환을 하면서 나눗셈을 수행해야 할 수 있다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;
		
		// 단, 0으로 나누거나 나머지 값은 존재하지 않는다. 
		float divideResult = a / b; // 나눈 값만 표시, 나머지 값은 버린다. 
		int remainResult = a % b;
		
		Console.WriteLine(divideResult);
		Console.WriteLine(remainResult);
	}
}
  • 저것은 이미 정수값을 대입하는 것이므로 다음과 같이 수행되어야 한다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;
		
		// 단, 0으로 나누거나 나머지 값은 존재하지 않는다. 
		float divideResult = a / (float)b; // 나눈 값만 표시, 나머지 값은 버린다. 
		int remainResult = a % b;

		Console.WriteLine(divideResult);
		Console.WriteLine(remainResult);
	}
}

  • 이렇게 float를 캐스팅해야 정상적인 결과값이 왼쪽에 대입되는 것.
  • 그래서 실수가 벌어질 수 있는 구간이 이런 부분일 수 있다.
  • 다음은 복합 연산자로 간결히 적어보는 예제.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		// 대입 연산자를 통해 a에 30을 더한 값을 a에 대입.
		// a = a + 30;
		a += 30;
		
		Console.WriteLine(a);
	}
}

  • 이제 비교 연산자를 통해 플레이어의 체력바를 다양한 색으로 나타내주는 것 등을 생각할 때 프로그램 내부에서 연산할 것이다.
  • 결과는 bool 타입, true 혹은 false로 나타난다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		// a = a + 30;
		a += 30;

		Console.WriteLine(b < 4);
		Console.WriteLine(b > 4);
	}
}

  • 애초에 bool 타입이니 한 번 살펴볼 것이 있다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		// a = a + 30;
		a += 30;

		bool c = b < 4;

		Console.WriteLine(c);
	}
}

  • 같다, 다르다, 이상, 이하 등의 조건도 줄 수 있다.
  • 이번엔 논리 연산자로 예시 사항을 한 번 만들어보도록 할 것이다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		bool isGrounded;
		bool hasUserInput;
		bool isPlayerAlive;
		
		Console.WriteLine();
	}
}
  • 당연히 bool 타입으로 결과가 도출될 것이다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;

		Console.WriteLine(isGrounded && hasUserInput && isPlayerAlive);
	}
}
  • 저러면 false가 발생. 키를 안눌렀으니까.
  • 그렇다면 or을 쓰면?
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;

		Console.WriteLine(isGrounded || hasUserInput || isPlayerAlive);
	}
}

  • true가 발생한다. 하나라도 true이므로.
  • 이제 어떤 식으로 가져갈 것인가에 대해서는 다음을 살펴보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;

		bool canJump = isGrounded || hasUserInput || isPlayerAlive;

		Console.WriteLine(canJump);
	}
}

  • 따로 변수를 두어 사용하는 셈.
  • 이제 not 연산자를 사용해보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int a = 7;
		int b = 3;

		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;

		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		Console.WriteLine(!isPlayerAlive);
	}
}

  • 죽은 상태를 알아보기 위해 변수 하나를 선언하는 것보다 not 연산자를 사용해보는 것이다.
  • 복잡한 과정 없이 살았다와 안 살았다 식으로 생각하면 될 것.
  • 다음은 증감 연산자를 보도록 하자.
  • 들어가기 앞서 전위 증감과 후위 증감에 대해 적절히 이해할만한 사진을 보고 진행하자.

<feat. 방식의 차이일 뿐 결과는 동일하다>

csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;
		
		// 1더하는 상황이면 증감 연산자 사용은 다음과 같다.
		Console.WriteLine(a++);
		Console.WriteLine(a);
	}
}
  • 출력문에 후위 증가로 했을 때 7로 되어 있는데 바로 다음줄에서는 8이 반영된 것을 알 수 있다.
  • 전위 증가로 하여 앞과 반대로 한다면?
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;
		
		// 1더하는 상황이면 증감 연산자 사용은 다음과 같다.
		Console.WriteLine(++a);
		Console.WriteLine(a);
	}
}
  • 이러면 더하는 연산을 먼저 하고 넣어준다.
  • 재밌는 실험을 아래에 해보자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;
		
		// 1더하는 상황이면 증감 연산자 사용은 다음과 같다.
		a = a++;
		Console.WriteLine(a);
		a = a++;
		Console.WriteLine(a);
		a = a++;
		Console.WriteLine(a);
		a = a++;
		Console.WriteLine(a);
	}
}
  • 대입 연산자의 역할은 a를 넣어줌으로써 끝났다. 그러니까 복사본이 하나 발생하여 넣어주는 형식이다. 메모리에 대한 사항이 나오면 좀 더 정확히 이해할 수 있다.
  • 뭐 이렇게 하면 아래와 같이 정상적으로 나오긴 한다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;
		
		// 1더하는 상황이면 증감 연산자 사용은 다음과 같다.
		a = ++a;
		Console.WriteLine(a);
		a = ++a;
		Console.WriteLine(a);
		a = ++a;
		Console.WriteLine(a);
		a = ++a;
		Console.WriteLine(a);
	}
}

  • 카운팅이 제대로 안된다고 본다면 이런 현상일듯.
  • 그래서 후위 연산은 값을 건네준 다음 연산을 한다이고 전위는 반대.

3. 조건문

3.1. 개요

  • 엑셀에서 쓰던 if랑 다를 것은 없음.
  • 참이면 수행할 것과 거짓일 경우 수행할 것의 분기가 나뉜다. 즉, 로직을 짜게 된다는 것이다.
  • if문이 없으면 프로그래밍 불가이긴 하다. 정확히는 친절하게 나온 것을 사용하지 못한다고 봐야 한다.
  • if문을 어렵다기 보다는 잘 사용하는 방법의 문제이다.
  • 지금은 어떻게 사용하나 정도만 볼 것.
  • 다른 명칭은 분기문이라고도 불린다.
  • 플로우차트 등으로 표현되기도 한다.

3.2. 사용법

  • 바로 하나 해보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;

		if (false)
		{
			Console.WriteLine("조건 충족");
		}
	}
}
  • 아무것도 나오지 않음.
  • if문 괄호 안에 true를 넣으면
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;

		if (true)
		{
			Console.WriteLine("조건 충족");
		}
	}
}
  • 최종적으로는 bool 타입이 들어간다는 이야기.
  • 비교 연산자의 경우 충족이 되거나 안되거나 하든 bool 타입 변환.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;

		if (a > 5)
		{
			Console.WriteLine("조건 충족");
		}
	}
}
  • 뭐든 bool 타입으로 반환되어 결과를 출력하지 말지를 결정하게 될 것.
  • if문에는 직관적인 사항을 적어주는 것이 좋다.
  • 이번에는 비틀어서 해보도록 하자. 조건은 b가 5 초과이면서 a가 2 이하일 때로 해본다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 7;
		int b = 3;

		// b가 5 초과이면서 a가 2 이하일 때
		if (b > 5 && a <= 2)
		{
			Console.WriteLine("조건 충족");
		}
	}
}

<if에서 절대란 것은 없다. 사실 모든 것은 절대란 없다.>

  • 그런데 조건식들을 적을 때 반드시란 것은 없다.
  • 조건이 난해하게 얽힐 때, 길어지면 길어질수록 코드를 보기 힘들다.
  • 따라서 아래와 같이 사용한다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 1;
		int b = 7;

		// b가 5 초과이면서 a가 2 이하일 때
		if (b > 5)
		{
			if(a <= 2)
			{
				Console.WriteLine("조건 충족");
			}
		}
	}
}
  • 중첩 형태에서도 충분히 가능하다. 간단한 것을 맨 위로 복잡한 수식은 아래로 두는 것이 가시적으로 좋을 수 있다.
  • if문이랑 페어로 나오는 것이 else이다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int a = 1;
		int b = 7;

		// b가 5 초과이면서 a가 2 이하일 때
		if (b > 5)
		{
			Console.WriteLine("b는 초과다");
		}
		else
		{
			Console.WriteLine("b는 초과가 아니다.");
		}
	}
}

  • 그래서 조건에 부합하지 않는 경우에도 실행되는 구문을 붙이고 싶을 때 이렇게 둘 중 하나는 반드시 수행이 될 수 있을 것이다.
  • 다음으로는 뭔가 점수 분류 같은 것을 시행했을 때의 상황을 생각해보도록 하자. 80점 초과면 A 등의 등급을 매길 때 if문 만으로 작성해보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int score = 75;
		if (score > 80)
		{
			Console.WriteLine('A');
		}
		if (score > 60)
		{
			Console.WriteLine('B');
		}
		if (score > 40)
		{
			Console.WriteLine('C');
		}
		if (score > 20)
		{
			Console.WriteLine('D');
		}
		else
		{
			Console.WriteLine('F');
		}
	}
}

  • 그런데 이렇게 적으면 A는 False라서 출력을 하지 않고 B, C, D에 대해서는 참이라 True로 인해 출력이 되며 else는 충족이 되는 조건이 있었기 때문에 Skip을 한 셈이다.

<불편..>

  • 원하는 것이 위와 같은 방향이 아닐 것이다. 그래서 키워드 자체는 if 앞쪽에 else를 적어줘야 한다는 것이다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int score = 75;
		if (score > 80)
		{
			Console.WriteLine('A');
		}
		else if (score > 60)
		{
			Console.WriteLine('B');
		}
		else if (score > 40)
		{
			Console.WriteLine('C');
		}
		else if (score > 20)
		{
			Console.WriteLine('D');
		}
		else
		{
			Console.WriteLine('F');
		}
	}
}

<편안~>

  • 이렇게 해야 B만이 뜬다.
  • if문을 탈 때, 아래로 내려가는데 else if에 충족되면 나머지는 skip해버린다.
  • 즉, else if문으로 여러 조건문을 내려가며 사용할 수 있다.
  • 예시로 체력바 색깔이나 유저 등급 등에 사용할 수 있다.

3.3. 중첩조건문

  • 2중과 3중 정도까진 괜찮지만 많아진다면 문제이다.

<중첩과 중복이 늘어나면 산으로 간다고 생각할 것>

  • 구동은 and 연산자와 비슷하게 움직인다.

3.4. switch

  • if문으로만 쓰면 생각보다 공간을 많이 차지하다 보니까 묶어서 처리할 수 있는 수단이 있는데 그게 switch.
  • 이것을 등급으로 환산하는 것을 switch로 바꿔서 보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int score = 75;

		switch (score)
		{
			case (>90):
				Console.WriteLine('A');
				break;
			case (>80):
				Console.WriteLine('B');
				break;
			case (>70):
				Console.WriteLine('C');
				break;
			case (>60):
				Console.WriteLine('D');
				break;
			default:
				Console.WriteLine('F');
				break;
		}
	}
}

  • case가 무엇이냐를 알려주고 default에서 else와 같이 빠지게 되는 것.
  • 하지만 조건문을 case에서 걸기에는 꽤 난이도가 있다.
  • 그래서 연산자를 case 쪽에 적용시켜서 사용하여 접근하는 방식도 가능.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		int score = 75;
		
		switch (score/10)
		{
			case 9:
				Console.WriteLine('A');
				break;
			case 8:
				Console.WriteLine('B');
				break;
			case 7:
				Console.WriteLine('C');
				break;
			case 6:
				Console.WriteLine('D');
				break;
			default:
				Console.WriteLine('F');
				break;
		}
	}
}

  • 한번에 로직을 묶어서 지원하는 방식도 있고 switch 식이라는 것도 존재한다. 물론 switch 식은 class를 배우고 나서 좀 더 깔끔하게 쓸 수 있다. 한 번씩 찾아보는 것도 괜찮은 방법일지도?
  • 하지만 주의점이 있다. switch를 C#에서는 잘못된 것을 잘 보정은 해주나 로우 레벨에서는 break 없어도 문법적으로 허용을 했으나 밑에 것까지 break를 만날 때까지 수행을 했던 것이 존재한다.
  • 그래서 로직이 끝나면 break를 걸어주고 case를 명확하게 해줘야 한다.
  • 특정 상태에 대한 변환이 필요할 때 많이 사용한다.

3.5. 분기 설계

  • 만일 대충 이런 상황일 때는?
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int score = 95;  
		string grade;

		// 잘못된 순서  
		if (score >= 60)  
		{  
			grade = "C";  
		}  
		else if (score >= 80)  
		{  
			grade = "B";      // 영원히 실행되지 않습니다  
		}  
		else if (score >= 90)  
		{  
			grade = "A";      // 영원히 실행되지 않습니다  
		}  
		else  
		{  
			grade = "F";  
		}
		Console.WriteLine(grade);

	}
}
  • 실행했을 때는 C가 나온다. else if가 충족되는 조건에서는 아랫것은 다 skip 했기 때문이다.
  • 따라서 조건의 순서를 무척 신경써야 한다.
  • 그래서 if문을 처음 다루거나 난해한 경우에는 메모장이나 그런 곳에 그려볼 필요는 있음.
  • 마인드맵처럼 그리면 코드 쓰는 것은 상당히 용이해진다.
  • 구조를 잡으면서 가야할지 보면서 갈 필요는 있고 도식화가 좋음.
  • 낙서만 하면 된다. 전문적이게 다룰 필요도 없음.

3.6. 삼항연산자(2)

  • 가령 이런 코드가 있다고 해보자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		bool isPlayerMove = true;

		if (isPlayerMove)
		{
			Console.WriteLine("플레이어 이동 애니메이션 적용");
		}
		else
		{
			Console.WriteLine("이동중이 아니었다.");
		}
	}
}

  • 그런데 이것을 다른 것에 담아보도록 하자.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		bool isPlayerMove = true;
		bool isAnimationPlay;

		if (isPlayerMove)
		{
			isAnimationPlay = true;
		}
		else
		{
			isAnimationPlay = false;
		}
		Console.WriteLine(isPlayerAlive);
	}
}

  • 출력했을 때 true가 출력하게 될 것이다.
  • 그런데 삼항 연산자를 쓰게 되면 축약이 가능하다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		bool isGrounded = true;
		bool hasUserInput = false;
		bool isPlayerAlive = true;
		bool canJump = isGrounded && hasUserInput && isPlayerAlive;

		bool isPlayerMove = true;
		string isAnimationPlay;

		isAnimationPlay = isPlayerMove == true ? "재생" : "멈춤";
		
		Console.WriteLine(isPlayerAlive);
	}
}

  • 물론 입문자에게 삼항연산자가 익숙하진 않는다. 반드시란 것은 아니다. 딱 명칭 정도만 알면 좋을듯

4. 보충 설명

4.1. string

  • 긴 문장을 이전 실습처럼 일일이 Console.WriteLine 등으로 사용할 것 없이 사용하는 방법이 존재한다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		string name = "mkl";
		int level = 25;
		int hp = 65;
		
		// 플레이어 이름은 mkl입니다. 레벨은 25며, 체력은 65입니다.
		// 이런 형식을 한 줄에 써보는 것. 여기에 '자리 표시자'라는 개념이 들어간다.
		Console.WriteLine("플레이어 이름은 {0}입니다. 레벨은 {1}며, 체력은 {2}입니다.",
			name, level, hp);
	}
}

  • 저 {}가 자리 표시자이다.
  • 그런데 쓰기 불편할 수 있으므로 '문자열 보간'을 사용하는 것이다.
  • 다음과 같은 것이 있다.
csharp
using System;

public class Program
{
	public static void Main(string[] args)
	{
		string name = "mkl";
		int level = 25;
		int hp = 65;
		
		// 문자열 보간
		Console.WriteLine($"플레이어 이름은 {name}입니다. 레벨은 {level}며, 체력은 {hp}입니다.");
	}
}

4.2. 정리

  • 프로그램 언어 쪽에서는 문자열을 사용하는 경우가 많을 것.
  • 현재까진 로직 제어까지 다가온 것.
  • 프로그래밍 언어 문법과 기능 사용할 때야말로 연습이 제대로 된다고 보면 된다.
  • if문을 어떻게 분기를 나눌까를 생각해볼 것.