《人生的人生博弈》中对负数的理解模数

问题描述 投票:-1回答:1

[我正在阅读'用python自动化无聊的东西',并且无法用%运算符理解一个简单的表达式。表达式为leftCoord = (x - 1) % WIDTH,在循环的第一次迭代中其计算结果为(0 - 1) % 60。在我看来,%运算符应该计算除法的余数。为什么将其评估为9?

这是程序中要讨论的表达式之前的部分:

import random,time,copy

WIDTH = 60
HEIGHT = 20

# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
    column = [] # Create a new column.
    for y in range(HEIGHT):
        if random.randint(0,1) == 0:
            column.append('#') # Add a living cell.
        else:
            column.append(' ') # Add a dead cell.
    nextCells.append(column) # nextCells is a list of column lists.

while True: # Main program loop.
    print('\n\n\n\n\n') # Separate each step with newlines.
    currentCells = copy.deepcopy(nextCells)

    # Print currentCells on the screen:
    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y], end='') # Print the # or space.
        print() # Print a newline at the end of the row.


    # Calculate the next step's cells based on current step's cells:
    for x in range(WIDTH):
        for y in range(HEIGHT):
            # Get neighboring coordinates:
            # % WIDTH ensures leftCoord is always between 0 and WIDTH -1
            leftCoord  = (x - 1) % WIDTH
            rightCoord = (x + 1) % WIDTH
            aboveCoord = (y - 1) % HEIGHT
            belowCoord = (y + 1) % HEIGHT
python-3.x modulus
1个回答
0
投票

为了示例,假设您使用的是10x10的表。

当第一个数字小于第二个数字时,%运算符不太直观。尝试进入交互式python shell并运行4%10。尝试使用8%10。请注意,如何始终获得相同的数字?那是因为除法的答案是0 ...而您的整数被剩余。对于表中的大多数数字,模量根本不起作用。

现在尝试-1%10(模拟这对第一行的作用)。它给您9,指示底行。如果您运行10%10(模拟最下面的行),它将得到0,表示最上面的行。有效地,这使表“自动换行” ...第一行中的单元格影响底部,反之亦然。它还缠绕在侧面。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.