Math类中常用的方法
//abs方法:取绝对值
int absNum=-3;
System.out.println(absNum+"的绝对值为:"+Math.abs(absNum));
//floor方法:向下取整
double number=32.9;
System.out.println(number+"向下取整后:"+(int)Math.floor(number));
//ceil方法:向上取整
System.out.println(number+"向上取整后:"+(int)Math.ceil(number));
//max方法:取最大值
//min方法:取最小值
int One=32,Two=22,Three=100;
System.out.println("最大值为:"+Math.max(One, Math.max(Two, Three)));
System.out.println("最小值为:"+Math.min(One, Math.min(Two, Three)));
// round方法:四舍五入
double roundNumOne=3.2;
double roundNumTwo=0.5;
double roundNumThree=-2.3;
double roundNumFour=-2.7;
System.out.println(roundNumOne+"四舍五入后:"+Math.round(roundNumOne));
System.out.println(roundNumTwo+"四舍五入后:"+Math.round(roundNumTwo));
System.out.println(roundNumThree+"四舍五入后:"+Math.round(roundNumThree));
System.out.println(roundNumFour+"四舍五入后:"+Math.round(roundNumFour));
//random方法:随机数
System.out.println("100以内随机数:"+(int)(100*Math.random()));
// pow方法:幂函数
int powNum=2;
System.out.println(powNum+"的2次方为:"+(int)Math.pow(powNum, 2));
System.out.println(powNum+"的3次方为:"+(int)Math.pow(powNum, 3));
// sqrt方法:开根号
int sqrtNum=64;
System.out.println(sqrtNum+"开根号后:"+(int)Math.sqrt(sqrtNum));
运行结果:
-3的绝对值为:3
32.9向下取整后:32
32.9向上取整后:33
最大值为:100
最小值为:22
3.2四舍五入后:3
0.5四舍五入后:1
-2.3四舍五入后:-2
-2.7四舍五入后:-3
100以内随机数:6
2的2次方为:4
2的3次方为:8
64开根号后:8
结合案例
输出大等于n的最小的完全平方数。
若一个数能表示成某个自然数的平方的形式,则称这个数为完全平方数。
import java.util.*;
public class 大等于n的最小的完全平方数 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("输入一个整数:");
long n=sc.nextInt();
double OpenRoot =Math.sqrt(n);//将这个数开平方根
long wholeNum=0;//定义一个完全平方数变量
if(n<=0){//排除这个数小于等于零的情况
wholeNum=0;
}
if(((long)OpenRoot*(long)OpenRoot)==n)//如果这个开平方根数的平方等于输入的这个数
wholeNum=(long)OpenRoot;//则此数为等于n的最小完全平方数
else wholeNum=(long) OpenRoot+1;//否则+1,将+1后的数的值赋给完全平方数变量
//输出这个大于n的最小完全平方数
System.out.println("大于或等于【"+n+"】的最小完全平方数是:"+(int)Math.pow(wholeNum, 2));
}
}
输出结果:
输入一个整数:32
大于或等于【32】的最小完全平方数是:36
【Moment】:大雨涤走幽暗,日出席来温暖,你久久勇敢。