数据类型的转换
时间:2021-02-25 11:44:08
收藏:0
阅读:0
类型转换
基本类型优先级
低----------------------------------------------------→高
byte , short , char , int , long , float , double
转换规则
1. 强制转换(由高转低)
int i = 128;
byte b = (byte)i;//内存溢出,输出结果出现问题
2. 自动转换(由低转高)
int i =128;
double d = i;
注意点:
1.不能对布尔值进行转换
2.不能把对象类型转换成不相干类型
3.在把高容量转换到低容量时,使用强制转换
4.转换时可能出现内存溢出,或精度问题
操作较大数时,注意溢出问题
int money = 10_0000_0000;//遇到较长数字可以添加_,不影响运算
int years = 20;
int total = money*years;//计算时已经溢出
long total2 = money*years;//默认是int类型,转换前已经存在问题(先运算,后赋值)
long total3 = money*((long)years);//做法是先把一个数转换成long类型
评论(0)