当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Guava IntMath mod()用法及代码示例


Guava IntMath类的mod(int x,int m)方法接受两个参数x和m,并用于计算m下的x模量值。

用法:

public static int mod(int x, int m)

参数:此方法接受两个参数x和m,它们是整数类型,并计算x模m。


返回值:该方法返回x mod m,该值将是小于m的非负值。

异常:如果m <= 0,则方法mod(int x,int m)引发ArithmeticException。

以下示例说明了mod(int x,int m)方法:

范例1:

// Java code to show implementation of 
// mod(int x, int m) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int x1 = -84; 
        int m1 = 5; 
  
        int ans1 = IntMath.mod(x1, m1); 
  
        // Using mod(int x, int m) 
        // method of Guava's IntMath class 
        System.out.println(x1 + " mod " + m1 + " is:" + ans1); 
  
        int x2 = 14; 
        int m2 = 6; 
  
        int ans2 = IntMath.mod(x2, m2); 
  
        // Using mod(int x, int m) 
        // method of Guava's IntMath class 
        System.out.println(x2 + " mod " + m2 + " is:" + ans2); 
    } 
}

输出:

-84 mod 5 is:1
14 mod 6 is:2

范例2:

// Java code to show implementation of 
// mod(int x, int m) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    static int findMod(int x, int m) 
    { 
        try { 
            // Using mod(int x, int m) 
            // method of Guava's IntMath class 
            // This should throw "ArithmeticException" 
            // as m <= 0 
            int ans = IntMath.mod(x, m); 
  
            // Return the answer 
            return ans; 
        } 
        catch (Exception e) { 
            System.out.println(e); 
            return -1; 
        } 
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int x = 14; 
        int m = -3; 
  
        try { 
            // Function calling 
            findMod(x, m); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}

输出:

java.lang.ArithmeticException:Modulus -3 must be > 0

参考:
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#mod-int-int-



相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 Java Guava | mod() method of IntMath Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。