← 中文资源

简体中文版本

floorDiv 与 floorMod 回绕

截断除法的余数跟随被除数符号,Math.floorDiv 向下取整、Math.floorMod 恒落在 0..除数-1,环形缓冲负步长回绕全靠它。

阅读英文原文

实现说明

floorDiv 与 floorMod 回绕的核心是类 CircularIndexing和函数 main。 迭代发生在 for (int step : new int[] {3, -2, -6}) 内部——循环之外的语句只执行一遍。

使用要点

  • 演示输出是带标签的(head=、plain %:、floorMod:),每个操作都会留下自己的一行标注。

常见问题

运行「floorDiv 与 floorMod 回绕」会打印什么?

整个文件跑完,输出行以 head=、plain %:、floorMod: 这类前缀开头。

核心语句

int wrapped = Math.floorMod(head + step, capacity);
int capacity = 5;
int head = 1;

代码示例

public class CircularIndexing {

    public static void main(String[] args) {
        // 截断除法:商向零取整,余数符号跟随被除数
        System.out.println(-7 / 2 + " remainder " + -7 % 2);

        // floor 语义:商向下取整,余数符号跟随除数
        System.out.println(Math.floorDiv(-7, 2) + " remainder " + Math.floorMod(-7, 2));

        // 环形缓冲:head 前进或倒退任意步,负步长也能正确回绕到合法槽位
        int capacity = 5;
        int head = 1;
        for (int step : new int[] {3, -2, -6}) {
            int wrapped = Math.floorMod(head + step, capacity);
            System.out.println("head=" + head + " step=" + step + " -> slot " + wrapped);
        }

        // 负数直接用 % 会落到负槽位,floorMod 恒为非负
        System.out.println("plain %: " + (-2 % 5));
        System.out.println("floorMod: " + Math.floorMod(-2, 5));
    }
}