Typecast是C语言中将一种数据类型转换为另一种数据类型的方法。
有两种类型转换。
1.Implicit Type强制转换-这种转换是由编译器完成的。当在表达式中使用多个数据类型的变量时,编译器将转换数据类型以避免数据丢失。
这是使用C语言进行隐式类型转换的示例,
#include <stdio.h>
int main() {
int a = 10;
char b = 'S';
float c = 2.88;
a = a+b;
printf("Implicit conversion from character to integer : %d\n",a);
c = c+a;
printf("Implicit conversion from integer to float : %f\n",c);
return 0;
}输出结果
Implicit conversion from character to integer : 93 Implicit conversion from integer to float : 95.879997
2.Explicit Type强制转换-此转换由用户完成。这也称为类型转换。用户强制将数据类型转换为另一种数据类型。
这是用C语言进行的显式类型转换的语法,
(type) expression
这是使用C语言进行显式类型转换的示例,
#include <stdio.h>
int main() {
float c = 5.55;
int s = (int)c+1;
printf("Explicit Conversion : %d\n",s);
return 0;
}输出结果
Explicit Conversion : 6