사자자리
[C언어] 3주차 연산자 본문
증감 연산자
- 변수에만 사용할 수 있다.
구분 | 증감 연산자 | 연산 결과값 |
전위형 | ++ count | 1 증가된 변수 count의 값 |
-- count | 1 감소된 변수 count의 값 | |
후위형 | count ++ | 1 증가되기 전 변수 count의 값 |
count -- | 1 감소되기 전 변수 count의 값 |
#include <stdio.h>
int main(){
int count1 = 10;
int value1 = ++ count1;
printf("%d %d\n", count1, value1); // count1 = 11, value1 = 11
int count2 = 10;
int value2 = count2 ++;
printf("%d %d\n", count2, value2); // count2 = 11, value2 = 10
return 0;
}
논리 연산자
- 참과 거짓을 이용한 논리 연산 기능을 제공한다.
- 참(True): 0이 아닌 값. 보통 1을 사용한다.
- 거짓(False): 0
- 관계 연산자(<, >, <=, >=)보다 우선 순위가 낮다.
- OR 연산자는 shift + \(역슬래시) 키를 누르면 입력된다.
우선 순위: | ① NOT | ② AND | ③ OR | ||
a | b | !a | a && b | a || b | |
0 | 0 | → | 1 | 0 | 0 |
0 | 1 | 1 | 0 | 1 | |
1 | 0 | 0 | 0 | 1 | |
1 | 1 | 0 | 1 | 1 |
#include <stdio.h>
int main(){
int num = 50;
printf("%d\n", !num); // 50(True)에서 0(False)으로
printf("%d\n", num >= 40 && num <= 60); // 40 이상 60 이하이므로 1(True)
printf("%d\n", num == 0 || num == 100); // 0도 아니고 100도 아니므로 0(False)
return 0;
}
비트 연산자
- 각 비트 단위로 부울 연산을 한다.
AND | OR | XOR | NOT | |||
a | b | a & b | a | b | a ^ b | ~ a | |
0 | 0 | → | 0 | 0 | 0 | 1 |
0 | 1 | 0 | 1 | 1 | 1 | |
1 | 0 | 0 | 1 | 1 | 0 | |
1 | 1 | 1 | 1 | 0 | 0 |
#include <stdio.h>
int main(){
int a = 10; // 2진수: 00001010
int b = 12; // 2진수: 00001100
printf("%d\n", a & b); // 00001000 (10진수: 8)
printf("%d\n", a | b); // 00001110 (10진수: 14)
printf("%d\n", a ^ b); // 00000110 (10진수: 6)
printf("%d\n", ~a); // 11110101 (10진수: -11)
return 0;
}
비트 이동 연산자
이동 방향 | n번 이동하면 | 빈자리에는 | 예시 |
왼쪽: << n | 원래 숫자 × (2의 n승) | 0이 채워진다. | 0110(6) → 1100(12) |
오른쪽: >> n | 원래 숫자 ÷ (2의 n승) | 부호 비트가 채워진다. | 0110(6) → 0011(3) |
#include <stdio.h>
int main(){
int a = 40; // 2진수: 00101000
printf("%d\n", a<<2); //10100000 (10진수: 160)
printf("%d\n", a>>2); //00001010 (10진수: 10)
return 0;
}
조건 연산자
- 유일한 삼항 연산자
- 수식1 ? 수식2 : 수식3
- 수식1이 참일 때, 연산의 결과는 수식2
- 수식1이 거짓일 때, 연산의 결과는 수식3
#include <stdio.h>
int main(){
int a = 10;
int b = 20;
int min, max;
min = a<b ? a:b; // a<b가 참이면 min은 a, 거짓이면 min은 b
max = a>b ? a:b; // a>b가 참이면 max는 a, 거짓이면 max는 b
printf("min = %d\n", min);
printf("max = %d\n", max);
return 0;
}
연산자의 우선 순위: 단항 → 산술 → 관계 → 논리 → 대입 → 콤마
[백준] 2475번 검증수
#include <stdio.h>
int main() {
int x;
int sum = 0;
for (int i = 0; i < 5; i++){
scanf("%d", &x);
sum += x*x;
}
printf("%d", sum%10);
return 0;
}
문제를 읽자마자 떠오른 방법은 다섯 자리 숫자를 scanf를 이용해 각각 a, b, c, d, e로 입력받는 것이었다. 그러나 이 방법은 효율성과 일반성이 떨어지므로 for 반복문을 이용하는 방법을 사용하게 되었다.
[백준] 2588번 곱셈
#include <stdio.h>
int main() {
int n1, n2;
scanf("%d\n%d", &n1, &n2);
int n3 = n1 * (n2%10);
int n4 = n1 * ((n2/10)%10);
int n5 = n1 * (n2/100);
printf("%d\n",n3);
printf("%d\n",n4);
printf("%d\n",n5);
printf("%d\n",n1*n2);
return 0;
}
'C언어 > C언어 이론' 카테고리의 다른 글
[C언어] 5주차 배열과 문자열 (0) | 2022.05.20 |
---|---|
[C언어] 4주차 함수 (0) | 2022.05.14 |
[C언어] 4주차 제어문 (0) | 2022.05.14 |
[C언어] 2주차 (0) | 2022.04.29 |
[C언어] 1주차 #include <stdio.h> (0) | 2022.04.02 |
Comments