Type Casting (형변환)
형변환은 (type_name) expression 으로 가능하다.
예를 들어 원의 체적을 구하는 식을 계산하려 할 때 (int) 4/3 * PI * r * r * r 에서는 (int)가 type_name 이고 나머지가 expression 이다.
위 그림은 형 변환을 할 때의 서열이라고 생각하면 된다. int형과 float형을 계산한다면 float 형으로 결과가 저장되는 방식이다. float 나 double 에서 int 형으로 변환 할 때에는 소수점 밑 숫자들이 모두 내림처리된다. (반올림되지 않음)
예제를 보며 이해하는 편이 빠르다.
여담이지만 scanf 함수 쓸 때, 두 번째 parameter에 &를 넣지 않는 실수를 자주 한다.
그러고서 형변환 에 문제가 있나?? 하고 한참 삽질하기 전에 꼭 확인해야 한다... ㅜ
1. 계산과정에서의 형과 저장할 때의 형이 다르면 어떻게 되는지 보여줌. 마지막 출력이 정답이다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int iNum1, iNum2;
float fNum;
printf("Enter two integers. Ex 15 40\n");
scanf("%d %d", &iNum1, &iNum2);
//Calculated as Integer value and print as Integer value
printf("%d / %d = %d\n", iNum1, iNum2, iNum1 / iNum2); //0
//Calculated as Integer value and print as Float value
printf("%d / %d = %f\n", iNum1, iNum2, iNum1 / iNum2);
printf("---------------\n");
//Calculated as Integer Value and saved as float value
fNum = iNum1 / iNum2;
printf("%d / %d = %f\n", iNum1, iNum2, fNum);
//Calculated as Float value and saved as Float Value
fNum = (float)iNum1 / iNum2;
printf("%d / %d = %f\n", iNum1, iNum2, fNum);
system("pause");
return 0;
}
2. 성적 평균
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int iEngScore;
int iSciScore;
int iMathScore;
float fAverage;
scanf("%d", &iEngScore);
scanf("%d", &iSciScore);
scanf("%d", &iMathScore);
fAverage = ((float)iEngScore + iSciScore + iMathScore) / 3;
printf("%.2f", fAverage);
system("pause");
return 0;
}
3. 섭씨를 화씨로 바꾸되 정수로 출력
섭씨를 화씨로 바꾸는 식에서 (double) (9/5) * iDegCelcius + 32.0 을 해버리면 괄호 안에 있는 9/5 가 가장 먼저 형변환이 되지 않은 채로 계산이 되어 틀린 결과를 낸다. 곱하는 순서를 ((double) 9) * 9 / 5 * iDegCelcius + 32.0 을 해야 정밀도가 높아진다. 앞에서 부터 차례대로 계산이 되는 식이기 때문에 (double) 9 / 5 * iDegCelcius + 32.0 도 무방하다
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
//섭씨온도를 C라고 했을 때 그에 해당하는 온도 F = (9/5)C + 32
int iDegCelcius;
int iDegFahrenheit;
printf("Enter Degrees in Celcius.");
scanf("%d", &iDegCelcius);
iDegFahrenheit = (double)9 / 5 * iDegCelcius + 32.0;
printf("%d derees in Celcius is %d degrees in Fahrenheit\n", iDegCelcius, iDegFahrenheit);
system("pause");
return 0;
}
4. / * 계산
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int input_a;
int input_b;
int input_c;
float tmp;
printf("Enter integer input a b c \n");
scanf("%d %d %d", &input_a, &input_b, &input_c);
tmp = (float)input_a / input_b * input_c;
printf("%d / %d * %d = %f \n", input_a, input_b, input_c, tmp);
system("pause");
return 0;
}
5. 직각투영 (Orthogonal Projection), 선의 길이
printf 문에서 서식지정자를 쓸 때 int형 변수를 float 서식지정자 즉, %f에 매칭시킨다면 값이 깨진다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main(void) {
float x1, y1, x2, y2, xLen, yLen, result;
printf("Point 1(x1, y1) : ");
scanf("%f %f", &x1, &y1);
printf("Point 1(x1, y1) : ");
scanf("%f %f", &x2, &y2);
xLen = fabs(x2 - x1);
yLen = fabs(y2 - y1);
//float 형 유지하고 서식지정자에서 int를 받게
printf("Length of orthogonal projection to the X-Axis : %d\n", (int)xLen);
printf("Length of orthogonal proejction to the Y-Axis : %d\n", (int)yLen);
//int 형으로 바꾸고 서식지정자에서 Int를 받게
printf("Length of orthogonal projection to the X-Axis : %d\n", (int)xLen);
printf("Length of orthogonal proejction to the Y-Axis : %d\n", (int)yLen);
//int 형으로 바꾸고 서식지정자에서 float를 받게
printf("Length of orthogonal projection to the X-Axis : %f\n", (int)xLen);
printf("Length of orthogonal proejction to the Y-Axis : %f\n", (int)yLen);
//double 형으로 바꾸고 서식지정자에서 float를 받게
printf("Length of orthogonal projection to the X-Axis : %f\n", (double)xLen);
printf("Length of orthogonal proejction to the Y-Axis : %f\n", (double)yLen);
/*
By pythagoras' theorem, length of line is
d = sqrt(x2-x1)^2 + (y2 - y1)^2)
*/
result = sqrt(pow(xLen, 2) + pow(yLen, 2));
printf("Length of the line : %.2f\n", result);
system("pause");
return 0;
}