代码之家  ›  专栏  ›  技术社区  ›  ColorMyChicken

模运算不会产生负数

  •  0
  • ColorMyChicken  · 技术社区  · 6 年前

    我在java中有一个计算坐标的小方法。但是如果其中一个坐标是负数,我只得到0而不是负数。

    private static void highlightIslandBorders(Location loc) {
            World world = loc.getWorld();
    
            int sx = loc.getBlockX();
            sx -= sx % islandSize;
    
            int sz = loc.getBlockZ();
            sz -= sz % islandSize;
    
            if ((sx < 0) || (sz < 0)) {
                return;
            }
    
            int ex = sx + islandSize - 1;
            int ez = sz + islandSize - 1;
    
            int y = loc.getBlockY() - 1;
    
            Material cornerMat = Material.GLOWSTONE;
            world.getBlockAt(sx, y, sz).setType(cornerMat);
            world.getBlockAt(ex, y, sz).setType(cornerMat);
            world.getBlockAt(sx, y, ez).setType(cornerMat);
            world.getBlockAt(ex, y, ez).setType(cornerMat);
        }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   svdragster    6 年前

    你从哪里得到的0?

    int islandSize = 3;
    int sx = -100;
    
    System.out.println("Mod: " + (sx % islandSize));
    
    sx -= sx % islandSize;
    System.out.println("sx: " + sx);
    

    结果

    型号:-1
    SX:-99个