day02-数据类型转换_强制转换和小数的转换

This commit is contained in:
2026-04-19 16:26:17 +08:00
parent 3a9a5988eb
commit f01232f3dc
2 changed files with 45 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package com.inmind.type_cast01;
/*
数据转换---强制转换(重点)
强制转换的格式:
被转换到的数据类型 变量名 = (被转换到的数据类型)要被转换的数值;
数据类型 变量名 = (数据类型)被转数据值;
byte b1 = (byte) (b+i);
强制转换:当要把大范围的数据类型赋值给小范围的数据类型时,要使用强制转换
注意:强转的结果是会发生精度丢失,切忌使用
*/
public class Demo03 {
public static void main(String[] args) {
//定义字节变量
byte b = 1;
//定义整型变量
int i = 2;
//2者相加
int result = b+i;//自动转换1字节的byte b 自动提升为int
System.out.println(result);
//结果是一个字节就可以表示的数据,我们能不能使用字节来接收呢???可以
//byte result1 = (byte) b+i;//含义先将变量b强转为byte再加i由于i还是int类型还是自动提升了
byte result1 = (byte) (b+i);//含义:()在java中可以表示优先执行b+i先运算然后再使用强转格式
System.out.println(result1);
}
}

View File

@@ -0,0 +1,18 @@
package com.inmind.type_cast01;
/*
小数的强转为整数:直接将小数点后面的数给“砍掉”
*/
public class Demo04 {
public static void main(String[] args) {
//定义double变量
double d = 3.94;
System.out.println("变量d的值"+d);
//小数直接赋值给int型
int i = (int) d;
System.out.println("变量i的值"+i);
float f = 3.14F;
int i2 = (int) f;
System.out.println(i2);
}
}