몽상실현개발주의

[따배씨] 5.10 순서도 ~ 5.11 자료형 변환 본문

Language/C

[따배씨] 5.10 순서도 ~ 5.11 자료형 변환

migrationArc 2021. 5. 18. 16:47

[따배씨] 5.10 순서도 ~ 5.11 자료형 변환

따배씨 - 따라하며 배우는 C언어

5강 연산자, 표현식, 문장

5.10 순서도 Flowcharts

- skip

 

 

 

5.11 자료형 변환 Type conversions

#include <stdio.h>

int main(){
    /* promotions in assignments */
    short s = 64;
    int i = s;
    
    float f = 3.14f;
    double d = f;
    
    
    return 0;
}
  • 작은 자료형을 큰 자료형에 대입

 

 

#include <stdio.h>

int main(){
    /* demotion in assignments */
    float f = 3.14f;
    double d = f;
    
    d = 1.25;
    f = 1.25;
    f = 1.123;
      
    return 0;
}
  • 큰 자료형을 작은 자료형에 대입 -> Warning 발생
    • 정확도(유효숫자)에 문제가 발생 할 수 있음

 

 

#include <stdio.h>

int main(){
    /* ranking of types in operations */
    // long double > double > float
    // unsigned long long, long long
    // unsinged long, long
    // unsigned, int
    // shor int, unsinged short int
    // signed char, char unsinged char
    // _Bool
    
    double d = 1.2;
    float f = 1.123f;
    
    d = f + 1.234;
    f = f + 1.234;
    
    printf("%f\n", d);
    printf("%f\n", f);
    
    return 0;
}

 

 

 

/* automatic promotion of function arguments */
// 1. Functions without prototypes
// 2. Variadic functions (ellipsis)

 

 

 

#include <stdio.h>

int main(){
  	/* casting operators */
    double d = 1.2;
    int i = 0;
    
    d = (double)3.14f;
    i = 1.6 + 1.7;
    printf("%d\n", i);
    // 3
    i = (int)1.6 + (int)1.7;
    printf("%d\n", i);
    // 2
    return 0;
}
  • Casting operators: 자료형을 명시

 

 

#include <stdio.h>

int main(){
    char c;
    int i;
    float f;
    
    f = i = c = 'A';
    printf("%c %d %f\n", c, i, f);
  	// A 65 65.000000
    
    c = c + 2;
    i = f + 2 * c;
    printf("%c %d %f\n", c, i, f);
  	// C 199 65.000000
    
    c = 1106; // demolitions, 1106 = 0b10001010010, 0b01010010 = 1106 % 256 = 82 = 'R'
    printf("%c\n", c);
  	// R
    c = 83.99;
    printf("%c\n", c);
  	// S
    
    return 0;
}
  • char 는 저장되는 변수의 data type 에 따라 문자와 숫자로 변환 됨
  • 1106 은 2진수 11 bits, char 형이 8bits 이므로 하위 8bits 만 저장되어 82가 되고 82에 해당하는 문자인 'R' 이 출력
  • 83.99 의 경우도 작은 자료형으로 변환이 되므로, 데이터 손실이 발생하여 83이 저장되고 문자 'S' 가 출력

 

참고 : [C] 형 변환 Type Conversion

 

 

 

 


이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.

http://blog.naver.com/atelierjpro

 

실리콘 밸리의 프로그래머 : 네이버 블로그

안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.

blog.naver.com

http://www.inflearn.com/course/following-c

 

홍정모의 따라하며 배우는 C언어 - 인프런 | 강의

'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원

www.inflearn.com

Comments