吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C中的类型转换

C中的类型转换

来源:网络 | 更新时间:2022-01-08 14:16:16
类型转换基本上是从一种类型到另一种类型的转换。类型转换有两种类型:
  • 隐式类型转换
也称为“自动类型转换”。
  • 由编译器自行完成,无需用户的任何外部触发。
  • 通常在表达式中存在一种以上数据类型时发生。在这种情况下,会发生类型转换(类型提升)以避免数据丢失。
  • 变量的所有数据类型都升级为数据类型最大的变量的数据类型
bool -> char -> short int -> int -> 
       unsigned int -> long -> unsigned -> 
       long long -> float -> double -> long double
  • 隐式转换可能会丢失信息,符号可能会丢失(当有符号隐式转换为无符号时),并且可能发生溢出(当 long long 隐式转换为浮点数时)。
类型隐式转换示例:
// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII 
// value of 'a' is 97
x = x + y;

// x is implicitly converted to float
float z = x + 1.0;

printf("x = %d, z = %f", x, z);
return 0;
}
输出:
x = 107,z = 108.000000
  • 显式类型转换
这个过程也称为类型转换,它是用户定义的。在这里,用户可以对结果进行类型转换以使其成为特定的数据类型。 C中的语法:
(类型)表达式
类型表示最终结果转换成的数据类型。
// C program to demonstrate explicit type casting
#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int
int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}
输出:
sum = 2
类型转换的优点
  • 这样做是为了利用类型层次结构或类型表示的某些特性。
  • 它帮助我们计算包含不同数据类型变量的表达式。
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com