본문으로 건너뛰기

연산자 활용하기

서식 문자(%p, %X, %x)

%p : 주소를 16진수로 표시하는 서식 문자

#include <stdio.h>

int main(void){
int a = 10;
int b = 20;

printf("%d %d\n", a, b);
printf("%p %p\n", &a, &b); // 주소를 넣을 때는 &기호가 필요
}
실행 결과
    10 20
0029FF1C 0028FF18

%X, %x 서식 문자 : 16진수 대문자, 소문자로 변환

#include <stdio.h>

int main(void){
int a = 10;
int b = 20;

printf("a = %d, b = %d\n", a, b);
printf("a = %X, b = %x\n", a, b);
printf("&a = %p, &b = %p\n", &a, &b);
}
실행 결과
  a = 10, b = 20
a = A, b = 14
&a = 0028FF1C, &b = 0028FF18

자리 이동 연산자(<< 왼쪽, >>오른쪽)

<< 왼쪽 자리 이동 연산자 : 2를 곱한 것 과 같은 결과

#include <stdio.h>

int main(void){
printf("%d\n", 5 << 0); // 5
printf("%d\n", 5 << 1); // 10
printf("%d\n", 5 << 2); // 20
printf("%d\n", 5 << 3); // 40
printf("%d\n", 5 << 4); // 80
printf("%d\n", 5 << 5); // 160
}

>> 오른쪽 자리 이동 연산자 : 2를 나눈 몫이 됨

#include <stdio.h>

int main(void){
printf("%d\n", 25 >> 0); // 25
printf("%d\n", 25 >> 1); // 12
printf("%d\n", 25 >> 2); // 6
printf("%d\n", 25 >> 3); // 3
printf("%d\n", 25 >> 4); // 1
printf("%d\n", 25 >> 5); // 0
}

관계 연산자 ==

두 변수가 같으면 참을 반환, 다르면 거짓을 반환

  • = : 대입 연산자
  • == : 관계 연산자 (같다)
  • != : 관계 연산자 (다르다)
#include <stdio.h>

int main(void){
int a = 10;
int b = 20;

if (a == b)
printf("같다.\n");
else
printf("다르다.\n");
}
#include <stdio.h>

int main(void){
int a = 10;
int b = 20;

if (a = b) // 대입 연산자
printf("같다.\n");
else
printf("다르다.\n");
}
실행 결과
  같다

결과는 무조건 "같다." 가 출력 됨, 거짓은 0, 참은 0이 아닌 경우..

예제 풀이

#include <stdio.h>

int main(void){
int totalAmount;

printf("지폐로 교환할 액수를 입력하세요. \n");
scanf("%d", &totalAmount);

int won_50000 = totalAmount / 50000;
totalAmount = totalAmount % 50000;
printf("오만원권 %d 장\n", won_50000);

int won_10000 = totalAmount / 10000;
totalAmount = totalAmount % 10000;
printf("만원권 %d 장\n", won_10000);

int won_5000 = totalAmount / 5000;
totalAmount = totalAmount % 5000;
printf("오천원권 %d 장\n", won_5000);

int won_1000 = totalAmount / 1000;
totalAmount = totalAmount % 1000;
printf("천원권 %d 장\n", won_1000);

printf("지폐를 제외한 나머지 %d 원\n", totalAmount);
}
실행 결과
실행 결과:
지폐로 교환할 액수를 입력하세요.
68923
오만원권 1 장
만원권 1 장
오천원권 1 장
천원권 3 장
지폐를 제외한 나머지 923 원

홀짝 게임 만들기

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void){
srand(time(0));
int robot_num = rand();
int robot = robot_num % 2;

int minsu = 0;
printf("홀수면 1, 짝수면 2를 입력하세요.\n");
scanf("%d", &minsu);

printf("로봇이 만든 수 %d\n", robot_num);

if(robot % 2 == minsu) printf("민수가 이겼습니다. \n");
else printf("로봇이 이겼습니다.\n");
}