Java 運算子 % 和 /

wangyy發表於2018-01-12

/ 是除運算子,

%是取模運算子

區別:

/ 是普通的除法運算,如果除數和被除數都是整數,則商是取整

%是求餘數 

 

private static void test() {
        System.out.println("2/5 = " + 2 / 5);
        System.out.println("2%5 = " + 2 % 5);
        System.out.println("5/2 = " + 5 / 2);
        System.out.println("5%2 = " + 5 % 2);
        System.out.println("-5/2 = " + -5 / 2);
        System.out.println("-5%2 = " + -5 % 2);
        System.out.println("5/-2 = " + 5 / -2);
        System.out.println("5%-2 = " + 5 % -2);
        System.out.println("--------");
        System.out.println("2/5.0 = " + 2 / 5.0);
        System.out.println("2%5.0 = " + 2 % 5.0);
        System.out.println("5.0/2 = " + 5.0 / 2);
        System.out.println("5.0%2 = " + 5.0 % 2);
        System.out.println("-5.0/2 = " + -5.0 / 2);
        System.out.println("-5.0%2 = " + -5.0 % 2);
        System.out.println("5.0/-2 = " + 5.0 / -2);
        System.out.println("5.0%-2 = " + 5.0 % -2);
    }
執行結果:
2/5 = 0
2%5 = 2
5/2 = 2
5%2 = 1
-5/2 = -2
-5%2 = -1
5/-2 = -2
5%-2 = 1
--------
2/5.0 = 0.4
2%5.0 = 2.0
5.0/2 = 2.5
5.0%2 = 1.0
-5.0/2 = -2.5
-5.0%2 = -1.0
5.0/-2 = -2.5
5.0%-2 = 1.0

 

相關文章