當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Math.floorDiv()用法及代碼示例

java.lang.Math.floorDiv() 用於查找小於或等於代數商的最大整數值。此方法首先將第一個參數除以第二個參數,然後對結果執行 floor() 運算,並返回小於或等於商的整數。

用法

public static int floorDiv(int x, int y)
public static long floorDiv(long x, int y)
public static long floorDiv(long x, long y)

參數

x = the dividend 
y = the divisor

返回

This method returns the largest value that is less than or equal to the algebraic quotient.
  • 如果第一個參數是 int 或 long 值,第二個參數是 -1,則此方法將返回第一個參數作為輸出。
  • 如果第二個參數為零,則此方法將拋出 ArithmeticException。

例子1

public class FloorDivExample1
{
    public static void main(String[] args) 
    {
        int x = 25;
        int y= 3;
        // 25/3 value is 8.33 so floor(8.33) = 8 
        System.out.println(Math.floorDiv(x, y));
    }
}

輸出:

8

例子2

public class FloorDivExample2
{
    public static void main(String[] args) 
    {
        int x = -25;
        int y= 3;
        // -25/3 value is -8.333 so floor(-8.333) = -9 
        System.out.println(Math.floorDiv(x, y));
    }
}

輸出:

-9

例子3

public class FloorDivExample3
{
    public static void main(String[] args) 
    {
        long x = 6754883;
        int y = 0;
        // Second argument is zero, Output is Airthmetic Exception 
        System.out.println(Math.floorDiv(x, y));
    }
}

輸出:

Runtime Error:
Exception in thread "main" java.lang.ArithmeticException:/ by zero
	at java.lang.Math.floorDiv(Math.java:1052)
	at floorDivExample1.main(floorDivExample1.java:8)

示例 4

public class FloorDivExample4
{
    public static void main(String[] args) 
    {
        long x = 2148;
        long y= -1;
        // Input positive value and -1, Output first argument 
        System.out.println(Math.floorDiv(x, y));
    }
}

輸出:

-2148






相關用法


注:本文由純淨天空篩選整理自 Java Math.floorDiv() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。