Java笔记之Math类

本文介绍了Java中Math类的常用方法,并结合案例展示了如何找出大于或等于给定数n的最小完全平方数。完全平方数是指可以表示为某个自然数平方的数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
22次方为:4
23次方为: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】:大雨涤走幽暗,日出席来温暖,你久久勇敢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值