类型转换
概念
-
为什么需要“类型转换”
参与运算的两个操作数的数据类型,必须相同!
类型转换的类别:
-
隐式类型转换 (自动完成转换)
1)算数转换
2)赋值转换
3)输出转换
-
强制类型转化
-
隐式类型转换
-
算数转化
(+,-,*,/,%) char , int, long, long long, float, double 15 + 3.14 => 15.0 + 3.14
-
赋值转换
#include <stdio.h> int main(void) { int x; // 计算结果31.4 转换为int类型,因为赋值符号的左边变量的类型是int类型 x = 3.14 * 10.0; cout << x << endl; //31 return 0; }
-
输出转换
#include <stdio.h>
int main(void) {
printf("%c\n", 255+50); //305 -> 49 ('1');
printf("%d\n", 255+50); //305
return 0;
}
强制类型转换
#include <stdio.h>
int main(void) {
int x = 257 + 100;
printf("%d\n", x);
x = (char)257 + 100;//257前面加上一个括号,里面填要转换的类型
printf("%d\n", x);
return 0;
}