Unity 기본2 - C#의 연산자들
1. 사칙연산
+,-,*은 덧셈, 뺄셈, 곱셈인데
나눗셈 / 연산은 몫을 구해줌
%는 나머지를 구해주고
당연하지만 연산자는 우선순위가 있다.
곱셈, 나눗셈(나머지)을 먼저 하고 덧셈, 뺄셈은 뒤에 한다.
하지만 이런게 헷갈리면 먼저 연산하고 싶은걸 괄호 쳐서 하면 됨
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
int b = 3;
Debug.Log(a + b);
Debug.Log(a - b);
Debug.Log(a * b);
Debug.Log(a / b);
Debug.Log(a % b);
}
// Update is called once per frame
void Update()
{
}
}
만약 소수점까지 있는 정확한 나눗셈 연산을 하고 싶다면, a,b중 적어도 하나를 float형이나 double형으로 사용해야함
double형은 float형보다 정밀하고 자리를 더 많이 차지하지만 더 느리다.
게임에서는 보통 float를 사용
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log(5f / 3);
Debug.Log(5.0 / 2);
Debug.Log(5.0f / 2);
}
// Update is called once per frame
void Update()
{
}
}
5f/3에서 f는 5를 int형이 아닌 float형으로 바꿔달라는 것
둘 중 하나만 float형이어도 float로 결과를 내준다
5f와 3에서 5f는 float이고 3은 int니까 결과 5f/3은 1.666667로 float
5.0/3과 5.0f/3은 무슨 차이인가?
5.0을 double형으로 처리하고 5.0f는 float형으로 처리해준다
2. 비교연산
크냐, 작냐, 크거나 같냐, 작거나 같냐,
서로 같냐, 서로 다르냐
< , > , <= , >= , == , !=
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
int b = 3;
Debug.Log(a < b);
Debug.Log(a > b);
Debug.Log(a <= b);
Debug.Log(a >= b);
Debug.Log(a == b);
Debug.Log(a != b);
}
// Update is called once per frame
void Update()
{
}
}
결과는 비교 연산 결과로 True, False가 출력
참고로 할당연산 a = b로 하고 Debug.Log(a = b)를 해본다면?
신기하게 a = 5, b = 3인데 a에 3을 넣으면 a = 3이고 이 a = 3을 출력해줌
파이썬은 안그런것 같았는데
파이썬도 그러구나
참고로 비교연산은 사칙연산보다 우선순위가 낮다
a < b + c하면 b+c를 하고 나서 a < (b+c)가 된다
근데 모르겠으면 그냥 괄호치면 됨
3. 논리연산
!는 부정
&&은 and
||은 or
한번이 아니고 &&, ||으로 두번 써야함
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
int b = 3;
int c = 4;
int d = 5;
Debug.Log(!true);
Debug.Log(a < b | c < d);
Debug.Log(a < b & c < d);
}
// Update is called once per frame
void Update()
{
}
}
참고로 !은 파이썬의 부정 연산과는 다르게 int형에는 붙일 수 없다
bool형에만 붙일 수 있음
사칙연산, 비교연산보다 우선순위가 낮다.
예외로 부정 연산 !은 사칙연산보다 빠르다
역시 모르면 그냥 괄호 치면 된다
4. &와 &&의 차이
파이썬하면 &나 | 이렇게 하나만 썼던것 같은데... C#은 &&를 쓰네
C계열 언어는 논리연산자로 &&와 ||로 2번씩 쓴다고 한다
&&는 논리연산자이고 &는 비트연산자이다.
&&가 우리가 아는 and 논리연산이고, &는 비트 단위로 and연산을 수행한다
&&는 단축연산을 한다. A && B에서 A가 거짓이면 B는 보지 않고 A && B가 거짓이라고 한다.
&는 단축연산을 하지 않는다. A & B에서 A가 거짓이라고 판단되더라도, B까지 확인한다.
5. 할당 연산
=은 왼쪽에 오른쪽 값을 할당하는 연산
a = b + c;하면 a에 b+c값을 대입
할당연산과 사칙연산을 줄여서 쓸 수도 있다
a = a + 2;는 a += 2;로 줄여 쓸 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
int b = 3;
int c = 4;
int d = 5;
a = b + c; //7
a = a + 2; //9
a += 2; //11
a *= 2; //22
a -= 2; //20
a /= 2; //10
a++; //11
a--; //10
}
// Update is called once per frame
void Update()
{
}
}
증감연산이 가능한데,
a++;하면 a를 1 증가시키고, a--;하면 a를 1 감소시킨다.
++를 앞에 붙이냐, 뒤에 붙이냐도 차이가 있다.
int a = 5;이고 Debug.Log(a++);와 Debug.Log(++a);가 어떤 값이 나오는가?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
Debug.Log(a++);
Debug.Log(++a);
}
// Update is called once per frame
void Update()
{
}
}
Debug.Log(a++);로 먼저 a값을 출력하면 현재 a = 5이므로 5가 나오고
그리고 a에 1을 더한 다음,
Debug.Log(++a);로 먼저 a에 1을 더한 다음,
a를 출력하면 7이 나온다.
a++;하면 a를 넘기고 a에 1을 증가
++a;하면 a에 1을 증가시키고, a를 넘겨주는
6. 삼항연산
(조건) ? (조건이 참이면) : (조건이 거짓이면)
a = b > c ? 1 : 2;를 하면
b > c가 참이면 a에 1을 넣고 거짓이면 a에 2를 넣는다
너무 길게 쓰지말고, 괄호 등으로 가독성 좋게 쓸 것을 권고
a = (b > c) ? 1 : 2;가 더 보기 좋다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int a = 5;
int b = 3;
int c = 4;
int d = 5;
a = b > c ? 1 : 2;
Debug.Log(a);
}
// Update is called once per frame
void Update()
{
}
}
b > c는 거짓이므로 a에 2가 들어간
7. null
아무것도 아닌 것, 텅 비어있는 것
참고로 string s = null;, string c = "";을 할 때 s와 c는 서로 다르다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string s = null;
string c = "";
Debug.Log(s);
Debug.Log(c);
Debug.Log(s == c);
}
// Update is called once per frame
void Update()
{
}
}
"0살입니다"( string c = "")
"저도 모르겠는데요."(string s = null)은 다르다
8. ?? 연산자
C = (A) ?? (B)
A가 null이 아니면 C에 A를 넣고 A가 null이면 C에 B를 넣는다
A,B중 null이 아닌 값을 넣어줌
당연하지만 A,B가 둘다 null이 아니라면??
정의에 의해 A가 null이 아니니까 A를 넣는다
string s = null;
string s2 = "abc";
string s3 = s ?? s2;
이러면 s3에는 "abc"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string s = null;
string c = "abc";
string h = s ?? c;
Debug.Log(h);
}
// Update is called once per frame
void Update()
{
}
}
null이 있을 수 있을 때, null이 아닌 값을 반드시 할당하고 싶은 경우
str3 = str ?? (default);
str3에 null이 아니라 (default)값을 넣고 싶은 경우
+=처럼 ??=으로 줄여 쓸 수 있는데
str ??= str2;이면?
str = str ?? str2;
str이 null이면 str2를 넣고 str2가 null이면 str 그대로 간다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string s = null;
string c = "abc";
s ??= c;
Debug.Log(s);
}
// Update is called once per frame
void Update()
{
}
}
'프로그래밍 > Unity&C#' 카테고리의 다른 글
Unity 기본6 - C#의 컬렉션 List, Dictionary (0) | 2024.04.20 |
---|---|
Unity 기본5 - C# 배열에 대해 (0) | 2024.04.19 |
Unity 기본4 - 반복문 while, for문 (0) | 2024.04.18 |
Unity 기본3 - C#의 if와 switch 제어문 (0) | 2024.04.17 |
Unity 기본1 - object에 script 붙이기, c# 기본 자료형, using (0) | 2024.04.16 |