Jiyong's STUDY

강제형변환 본문

프로그래밍/C

강제형변환

Kingjiyong 2018. 3. 19. 01:56

만약 원래 자료형이 int었을때 float로


#include <stdio.h>


int main(){

int a=3.3; // 정수형에 소수점 << 소수점 손실의 경고문

printf("%.1f", (float)a); // 소수점 한자리만 나오게 a를 float형으로 변환

}


결과는 3.0 << 정수형에는 소수점 정보가 들어갈 수 없음


float에서 int로


#include <stdio.h>


int main(){

float a=1.1; // a=1.1

printf("%d", (int)a); // float형 a를 int형으로 변환

}


결과는 1 << 마찬가지


두개 이상의 정수형을 실수형으로


#include <stdio.h>


int main(){

int a=1; int b=2;

printf("%.1f", (float)a/b); // float형으로 형변환을 하여 a에서 b를 나눔

}


결과는 0.5


하지만


#include <stdio.h>


int main(){

int a=1; int b=2;

printf("%.1f", (float)(a/b));

}


으로 했을땐 결과는 0.0이다


(a/b)에서 int형으로 연산되어 정수자리의 정보만 남아있으므로

0을 float형으로 표현하게 되는 꼴이다



'프로그래밍 > C' 카테고리의 다른 글

strcmp, strncmp 설명, 비교  (0) 2018.05.15
strcat, strncat 설명, 비교  (0) 2018.05.15
strcpy strncpy 설명, 비교  (0) 2018.05.14
scanf gets fgets 문자열 입력 비교  (0) 2018.03.19
비트시프트연산  (0) 2018.03.19