为什么我的模运算符为1字节的输入返回两倍的块大小?

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

这里的想法是创建一个称为计算器的函数,该函数接受输入并将其与变量进行比较。将文件大小与块大小进行比较,如果有剩余,请将块大小加倍以适应使用情况。我的问题是,输入为1,我仍然得到8192?然而其他计算结果是正确的。我知道地板除法只会产生一个整数,而不是浮点数(我认为这样做是更好的方法,因为我想要实数),但是当我尝试对其进行浮点运算时,我会得到相同的回报。我也尝试过浮动到其他地方,或者结果不正确或与上面相同。当我颠倒模的顺序时,答案似乎是正确的,但我被告知这是错误的,并被告知要像您在此处看到的那样进行操作,并按此顺序进行底数分割和模。

所以我的问题是,为什么我得到8192的输入为1,但其余的都是正确的?

def calculator(somedata):                 # calculator function, 'somedata' is the input
    blocksize = 4096                      # what block size on the partition
                                          # calculate how many blocks are fully occupied
    fullblock = somedata // blocksize     # floor division will give back only the integer yes?
                                          # modulo to check whether there's any remainder
    bytesremain = somedata % blocksize    # which will say 1 or None unless I float yes?
                                          # return the block usage based on byte count?
    if bytesremain > 0:                   # if there's anything left over in the bytesremain
      return(blocksize * 2)               # double the block usage to 2
    return blocksize                      # otherwise return the block usage

print(calculator(1))                      # Should be 4096 
print(calculator(4096))                   # Should be 4096 
print(calculator(4097))                   # Should be 8192 
print(calculator(6000))                   # Should be 8192
python modulo floor-division
1个回答
0
投票

您可能正在寻找:

def calculator(somedata):
    blocksize = 4096
    fullblock = (somedata-1) // blocksize 
    return blocksize*(fullblock+1)
© www.soinside.com 2019 - 2024. All rights reserved.