一、绝对值
Math.abs(int a)
或 Math.abs(double a)
用于返回参数的绝对值。
demo:
public class MathAbsDemo {
public static void main(String[] args) {
int a = -10;
double b = -10.5;
System.out.println("整数的绝对值: " + Math.abs(a)); // 输出整数的绝对值
System.out.println("浮点数的绝对值: " + Math.abs(b)); // 输出浮点数的绝对值
}
}
二、向上取整
Math.ceil(double a)
返回大于或等于参数的最小整数。
demo:
public class MathCeilDemo {
public static void main(String[] args) {
double a = 10.2;
double b = 10.8;
System.out.println("10.2 向上取整: " + Math.ceil(a)); // 输出10.2向上取整的结果
System.out.println("10.8 向上取整: " + Math.ceil(b)); // 输出10.8向上取整的结果
}
}
三、向下取整
Math.floor(double a)
返回小于或等于参数的最大整数。
demo:
public class MathFloorDemo {
public static void main(String[] args) {
double a = 10.2;
double b = 10.8;
System.out.println("10.2 向下取整: " + Math.floor(a)); // 输出10.2向下取整的结果
System.out.println("10.8 向下取整: " + Math.floor(b)); // 输出10.8向下取整的结果
}
}
四、四舍五入
Math.round(float a)
或 Math.round(double a)
返回最接近参数的整数,如果有两个同样接近的整数,则结果取较大的整数。
demo:
public class MathRoundDemo {
public static void main(String[] args) {
double a = 10.2;
double b = 10.8;
System.out.println("10.2 四舍五入: " + Math.round(a)); // 输出10.2四舍五入的结果
System.out.println("10.8 四舍五入: " + Math.round(b)); // 输出10.8四舍五入的结果
}
}
五、随机数
Math.random()
返回一个介于 0.0 到 1.0 之间的随机浮点数。
demo:
public class MathRandomDemo {
public static void main(String[] args) {
System.out.println("随机数: " + Math.random()); // 输出一个随机数
}
}
以上就是本次分享的所有内容,感兴趣的朋友点个关注呀,感谢大家啦~