自动类型转换
自动类型转换指的是容量小的数据类型可以自动转换为容量大的数据类型。如图所示,黑色的实线表示无数据丢失的自动类型转换,而虚线表示在转换时可能会有精度的损失。
至于为什么double类型比long类型表示的范围大请移步double和long类型:
自动类型转换
可以将整型常量直接赋值给byte、 short、 char等类型变量,而不需要进行强制类型转换,只要不超出其表数范围即可。
1 | short b = 12; //合法 |
强制类型转换
强制类型转换,又被称为造型,用于显式的转换一个数值的类型。在有可能丢失信息的情况下进行的转换是通过造型来完成的,但可能造成精度降低或溢出。
语法格式:
1 | (type)var |
运算符“()”中的type表示将值var想要转换成的目标数据类型。
强制类型转换
1 | double x = 3.14; |
基本类型转化时常见错误和问题
操作比较大的数时,要留意是否溢出,尤其是整数操作时。
常见问题一
1 | /** |