public class Main {
public static void main(String[] args){
System.out.println("正数:(9.12) = " + (int)9.12);
System.out.println("负数:(-9.12) = " + (int)-9.12);
}
}
2. Java三个取整函数 1. Math.ceil(double num);//ceil为天花板,意为向上取整 2. Math.floor(double num);//floor为地板,意为向下取整结果:向0取整, 忽略小数点后面的部分
(9.12) = 9 (-9.12) = -9
public class Main {
public static void main(String[] args){
System.out.println("正数:Math.ceil(9.12) = " + Math.ceil(9.12));
System.out.println("负数:Math.ceil(-9.12) = " + Math.ceil(-9.12));
System.out.println("---------------------------------");
System.out.println("正数:Math.floor(9.12) = " + Math.floor(9.12));
System.out.println("负数:Math.floor(-9.12) = " + Math.floor(-9.12));
}
}
3. Math.round(double num);//Math.round就是对num+0.5之后向下取整结果:
Math.ceil 向上取整 Math.floor向下取整 Math.ceil(9.12) = 10.0 Math.ceil(-9.12) = -9.0 --------------------------------- Math.floor(9.12) = 9.0 Math.floor(-9.12) = -10.0
public class Main {
public static void main(String[] args){
System.out.println("小数点后第一位>5");
System.out.println("正数:Math.round(10.68) = " + Math.round(10.68));
System.out.println("负数:Math.round(-10.68) = " + Math.round(-10.68));
System.out.println();
System.out.println("小数点后第一位=5");
System.out.println("正数:Math.round(10.5) = " + Math.round(10.5));
System.out.println("负数:Math.round(-10.5) = " + Math.round(-10.5));
System.out.println();
System.out.println("小数点后第一位<5");
System.out.println("正数:Math.round(10.46) = " + Math.round(10.46));
System.out.println("负数:Math.round(-10.46) = " + Math.round(-10.46));
System.out.println();
}
}
即为: [ Math.floor(x+0.5) ] (向下取整)
即将原来的数字加上0.5后再向下取整
c语言取整 1. 使用int强制转换(同Java)
使用int强制转换的结果就是去掉小数部分。 int a; a=int(1.2); //a=1 a=int(-1.2); //a=-12. 两个取整函数 1. 使用floor函数向下取整(同JavaMath.floor)
使用floor函数的结果是向下取整,即得到比该数小的最大整数,需要包含头文件math.h int a; a=floor(1.2); //a=1 a=floor(-1.2); //a=-22. 使用ceil函数向上取整(同JavaMath.ceil)
使用ceil函数的结果是向上取整,即得到比该数大的最小整数,需要包含头文件math.h int a; a=ceil(1.2); //a=2 a=ceil(-1.2); //a=-13. 若需要向最邻近整数取整(同JavaMath.round)
float b=1.2; int a; b=b>=0 ? b+0.5:b-0.5; a=int(b);
逻辑右移和算术右移 C语言
- 无符号数:逻辑右移
- 有符号数:没有明确定义,但几乎所有编译器都对有符号数使用算术右移
- Java只支持有符号数
- 支持选择右移模式:
- x>>k 算术右移
- x>>>k 逻辑右移
Java向0取整方法:
java默认向0取整
int a1 = 13;
int a2 = 14;
int a3 = 15;
int a4 = 16;
int a5 = 17;
int a6 = 20;
int b = 10;
System.out.println(a1 + " " + a1 / b);
System.out.println(a2 + " " + a2 / b);
System.out.println(a3 + " " + a3 / b);
System.out.println(a4 + " " + a4 / b);
System.out.println(a5 + " " + a5 / b);
结果:
13 1
14 1
15 1
16 1
17 1
13 -1
14 -1
15 -1
16 -1
17 -1
20 -2



