public class MathRoundExample {
public static void main(String[] args) {
// Math.round() 方法用于将浮点数四舍五入为最接近的整数。
// 它返回一个 long 类型的值,对于 float 类型的参数返回 int 类型。
// 示例 1: 正数
float num1 = 2.5f;
long result1 = Math.round(num1);
System.out.println("Math.round(" + num1 + ") = " + result1); // 输出: Math.round(2.5) = 3
// 示例 2: 负数
float num2 = -2.5f;
long result2 = Math.round(num2);
System.out.println("Math.round(" + num2 + ") = " + result2); // 输出: Math.round(-2.5) = -2
// 示例 3: double 类型
double num3 = 3.7;
long result3 = Math.round(num3);
System.out.println("Math.round(" + num3 + ") = " + result3); // 输出: Math.round(3.7) = 4
// 示例 4: double 类型负数
double num4 = -3.7;
long result4 = Math.round(num4);
System.out.println("Math.round(" + num4 + ") = " + result4); // 输出: Math.round(-3.7) = -4
}
}
Math.round() 方法用于将浮点数(float 或 double)四舍五入为最接近的整数。float 类型的参数,返回的是 int 类型的结果;对于 double 类型的参数,返回的是 long 类型的结果。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站