JUST GO
[C] 연산자(1) 본문
연산자의 기본 개념
- 수식(expression) : 연산자와 피연산자의 조합
- 연산자(operator) : 연산에 사용되는 기호
- 피연산자(operand) : 연산의 대상이 되는 값
- 모든 수식에는 반드시 값이 있다.
- 수식의 평가 : 수식의 값을 구하는 것

피연산자의 개수에 의한 분류

연산자의 기능에 의한 분류

산술 연산자

- 부호 연산자 +, - : 단항 연산자

- 나누기 연산자(/) : 피연산자가 둘 다 정수인 경우, 몫도 정수가 된다.

- 나머지 연산자(%) : 피연산자가 모두 정수인 경우에만 사용

ex - 나머지 연산자의 활용
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int items = 0; // 전체 항목 수
int pages = 0, left = 0;
int items_per_page = 0; // 한 페이지 당 항목 수
printf("항목수? ");
scanf("%d", &items);
printf("한 페이지 당 항목수? ");
scanf("%d", &items_per_page);
pages = items / items_per_page; // 페이지 수
left = items % items_per_page; // 남은 항목 수
printf("%d 페이지와 %d 항목\n", pages, left);
return 0;
}
피연산자의 형 변환 규칙
- 피연산자 중에 double형이 있으면, 나머지 피연산자를 double형으로 변환한다.

- 피연산자 중에 float형이 있으면, 나머지 피연산자(정수형)를 float형으로 변환한다.

- 피연산자 중에 float형이 있으면, 나머지 피연산자(정수형)를 float형으로 변환한다.

자동 형 변환
- 암시적인 형 변환
- 정수와 실수의 혼합 연산 시 수행되는 형 변환은 자동으로 처리

- 단항 연산자에서는 항상 정수의 승격이 일어난다.


ex - 정수와 실수의 혼합 연산
#define _CRT_SECURE_NO_WARNINGS
#define PI 3.141592 // 매크로 상수 정의
#include <stdio.h>
int main(void)
{
int radius = 0;
double area, perimeter;
printf("반지름? ");
scanf("%d", &radius);
area = PI * radius * radius; // PI가 실수이므로 radius를 double형으로 변환해서 연산
printf("원의 면적: %.2f\n", area);
perimeter = 2 * PI * radius; // PI가 실수이므로 radius를 double형으로 변환해서 연산
printf("원의 둘레: %.2f\n", perimeter);
return 0;
}
증감 연산자
- 변수의 값을 1만큼 증가시키거나 감소시키는 단항 연산자
- 증감 연산자의 의미

- 전위형과 후위형

'C > 학습내용' 카테고리의 다른 글
[C] 제어문(switch문) (0) | 2022.10.05 |
---|---|
[C] 제어문(if문) (0) | 2022.10.05 |
[C] 연산자(3) (1) | 2022.10.05 |
[C] 연산자(2) (1) | 2022.10.05 |
[C] C언어와 프로그래밍 개요 (0) | 2022.10.05 |