floorその数以下の最大の整数を返します。
round四捨五入の計算です。切り上げるときは、その数より大きい整数になります。
roundは「四捨五入」を意味し、アルゴリズムはMath.floor(x+0.5)、つまり元の数に0.5を加えてから切り捨てるので、Math.round(11.5)Math.round(11.5) の結果は12で、Math.round(-11.5) の結果は -11 です。
まず、以下の例を通して Java Math の floor、ceil、rint、round 各メソッドの出力結果を見てみましょう:
Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("浮動小数点数を入力してください:");
while(sc.hasNext()){
double num = sc.nextDouble();
System.out.println("Math.floor(" + num + ") = " + Math.floor(num));
System.out.println("Math.ceil(" + num + ") = " + Math.ceil(num));
System.out.println("Math.rint(" + num + ") = " + Math.rint(num));
System.out.println("Math.round(" + num + ") = " + Math.round(num));
}
}
}
上記のプログラムを実行して出力をテストしてください:
$ javac Test.java $ java Test 输入一个浮点数: 2.2 Math.floor(2.2) = 2.0 Math.ceil(2.2) = 3.0 Math.rint(2.2) = 2.0 Math.round(2.2) = 2 -2.2 Math.floor(-2.2) = -3.0 Math.ceil(-2.2) = -2.0 Math.rint(-2.2) = -2.0 Math.round(-2.2) = -2 -2.5 Math.floor(-2.5) = -3.0 Math.ceil(-2.5) = -2.0 Math.rint(-2.5) = -2.0 Math.round(-2.5) = -2 2.5 Math.floor(2.5) = 2.0 Math.ceil(2.5) = 3.0 Math.rint(2.5) = 2.0 Math.round(2.5) = 3 2.7 Math.floor(2.7) = 2.0 Math.ceil(2.7) = 3.0 Math.rint(2.7) = 3.0 Math.round(2.7) = 3 -2.7 Math.floor(-2.7) = -3.0 Math.ceil(-2.7) = -2.0 Math.rint(-2.7) = -3.0 Math.round(-2.7) = -3
出力の解析
1、Math.floor()切り捨て。つまり、この数より小さい最大の整数です。
Math.floor(2.2) = 2.0; Math.floor(-2.2) = -3.0; Math.floor(2.5) = 2.0; Math.floor(-2.5) = -3.0; Math.floor(2.7) = 2.0; Math.floor(-2.7) = -3.0;
2、Math.ceil()切り上げ。つまり、この数より大きい最小の整数です。
Math.ceil(2.2) = 3.0; Math.ceil(-2.2) = -2.0; Math.ceil(2.5) = 3.0; Math.ceil(-2.5) = -2.0; Math.ceil(2.7) = 3.0; Math.ceil(-2.7) = -2.0;
3、Math.rint()その値に最も近い整数を返します。
注意:そのような整数が2つ存在する場合、そのうちの偶数。
4、Math.round() 四捨五入ただし、引数が負の場合、理解しにくいかもしれません。ソースコードを直接見たほうが理解しやすいでしょう。戻り値が整数型であることに注意してください。
Math.round(x) = Math.floor(x + 0.5)
上記のコードを以下の例に当てはめてテストしてください:
Math.round(2.2) = 2; Math.round(-2.2) = -2; Math.round(2.5) = 3; Math.round(-2.5) = -2; Math.round(2.7) = 3; Math.round(-2.7) = -3
参考URL:https://blog.csdn.net/u012050154/article/details/52448260