首页 > 文章列表 > Modulo或Java的剩余时间

Modulo或Java的剩余时间

426 2025-03-14

Modulo或Java的剩余时间

Java中的模运算符(余数)

模运算符(%)返回两个数相除后的余数。 例如,对于整数 aba % b 计算 a 除以 b 的余数。

要点:

  • 如果被除数小于除数,则模运算的结果就是被除数本身。

语法:

a % b  // a是被除数,b是除数

计算商和余数:

int quotient = a / b; // 商
int remainder = a % b; // 余数

示例程序1:提取个位数

此程序演示如何使用模运算符依次提取一个整数的个位数:

public class RemainderExample {
    public static void main(String[] args) {
        int number = 6547;
        while (number > 0) {
            System.out.println(number % 10); // 输出个位数
            number /= 10; // 去掉个位数
        }
    }
}

输出:

7 4 5 6

示例程序2:计算商和余数

此程序计算一个整数除以另一个整数的商和余数:

public class QuotientRemainder {
    public static void main(String[] args) {
        int number = 6547;
        int remainder;
        int quotient;
        while (number > 0) {
            remainder = number % 10;
            System.out.println("余数: " + remainder);
            quotient = number / 10;
            System.out.println("商: " + quotient);
            number = quotient;
        }
    }
}

输出:

余数: 7 商: 654 余数: 4 商: 65 余数: 5 商: 6 余数: 6 商: 0

参考链接: