基本类型的运算规则(5条)
(1)结果的类型与最大类型一致
int/int=int 结果是int (3/2=1)
double/int=double 结果是double (3d/2=1.5)
基本类型
package day0201; public class Test4 { public static void main(String[] args) { System.out.println(3 / 2); System.out.println(3d / 2); } }
(2)byte\short\char三种比int小的整数
运算时,会先自动转换为int
Byte a = 3;
Byte b = 4;
Byte c = a + b; //int + int = int 错误
package day0201; public class Test4 { public static void main(String[] args) { System.out.println('s'+'b');//int 213 } }
(3)整数运算溢出
整数运算超出范围时,会舍弃溢出的值
Integer.max_value + 1 = 负数最小值
package day0201; public class Test4 { public static void main(String[] args) { System.out.println(Integer.MAX_VALUE + 1); System.out.println(300000000 * 60 * 60 * 24 * 365); System.out.println(300000000L * 60 * 60 * 24 * 365); } }
(4)浮点数运算不精确
2-1.9 = 0.10000000000000009
4.35*100 = 435.99999999999994
package day0201; public class Test4 { public static void main(String[] args) { System.out.println(2 - 1.9); System.out.println(2 - 1.8); System.out.println(2 - 1.7); System.out.println(4.35 * 100); System.out.println(4.36 * 100); System.out.println(4.37 * 100); } }
JAVA提供了精确计算的方法
(5)浮点数的特殊值
Infinity 无穷大 3.14/0
Nan not a number 负数开方
Math.sqrt(-3) = nan
package day0201; public class Test4 { public static void main(String[] args) { System.out.println(3.14 / 0); System.out.println(Math.sqrt(-3)); } }
基本类型的类型转换
小范围转换为大范围(自动转换)
大范围转小范围:强制转型
int a = 356;
Byte b = (byte)a;//100
浮点数转整数,小数直接舍弃
牛郎织女
牛郎织女星间距16.4光年
光速299792458米/秒
喜鹊身长0.46米
求牛郎织女相会需要多少只喜鹊
package day0204; public class Test1 { public static void main(String[] args) { long ly = 299792458L * 60 * 60 * 24 * 365; double s = 16.4 * ly; double r = s / 0.46; long num = (long) Math.ceil(r); System.out.println(num); } }
运算符
+-*/ |
四则运算 |
+ |
字符串连接 |
% |
取余/求模 |
== |
判断是否相等 |
!= |
判断是否不等 |
>/>=/</<= |
大小比较 |
&& |
逻辑与/短路与 |
|| |
逻辑或/短路或 |
! |
非 |
++/– |
自增/自减运算 |
?: |
三项运算 |
= |
赋值运算 |
+=/-=/*=//= |
复合赋值运算符 自动转型 |
() |
转型运算符 |
平年闰年
判断年号是否时闰年
package day0205; import java.util.Scanner; public class Test1 { public static void main(String[] args) { /** * 闰年条件能被4整除且不能被100整除 * 或者能被400整除 */ System.out.print("请输入年号:"); int i = new Scanner(System.in).nextInt(); if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) { System.out.println("是闰年"); } else { System.out.println("不是闰年"); } } }
自增自减
package day0206; public class Test1 { public static void main(String[] args) { int a; a = 5; System.out.println(a++); a = 5; System.out.println(++a); a = 5; int b = a++; System.out.println(a); a = 5; a = a++; System.out.println(a); } }
三项运算符
求三个值的最大值
package day0207; import java.util.Scanner; public class Test1 { public static void main(String[] args) { System.out.print("输入整数a:"); int a = new Scanner(System.in).nextInt(); System.out.print("输入整数b:"); int b = new Scanner(System.in).nextInt(); System.out.print("输入整数c:"); int c = new Scanner(System.in).nextInt(); // int max = a > b ? a : b; // max = max > c ? max : c; int max = a > b ? (a > c ? a : c) : (b > c ? b : c); System.out.println(max); } }