仅输入2的幂

2024-04-20 11:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个简单的问题,但我卡住了。你知道吗

我正在编写一个简单的程序来获取一个输入值,它是2的一个不同倍数。也就是说,它必须是2^x形式,包括1,也就是2^0=1。你知道吗

因此,唯一有效的输入是1, 2, 4, 8, 16, 32,等。如果用户输入3,我的程序将抛出一个错误。我还限制了从18192(其中8192 = 2**13)的输入。如果用户键入10000-30,我将抛出一个错误。你知道吗

这就是我目前所拥有的。你知道吗

def checkValue():
maxValue = 8192
while True:
    try:
        intValue = int(input('Please enter integer: '))
    except ValueError:
        print("Value must be an integer!")
        continue
    else:
        if intValue < 1:
            print("Value cannot be less than 1")
            continue
        elif intValue > 8192: 
            print("Value cannot be greater than 8192")
            continue
        else:
            return("The value is equal to " + str(intValue) )

必须有一种简单的方法来测试输入是否是2的幂。不过,我不知道如何在我当前的代码中加入这样的测试。由于我只接受14值作为有效输入(即1和2**13以下的值),也许这是最有效的测试?你知道吗

任何建议都将不胜感激。非常感谢。你知道吗


Tags: 用户程序键入value错误integerbeelse
3条回答

只需使用以2为底的对数,并检查数字是否为整数:

float.is_integer(math.log(x, 2)) # test if number is whole

这个怎么样?你知道吗

def checkValue():
    maxValue = 8192
    while True:
        try:
            intValue = int(input('Please enter integer: '))
        except ValueError:
            print("Value must be an integer!")
            continue
        else:
            if intValue in [1, 2, 4, 8, 16, 32]:
                return("The value is equal to " + str(intValue))
            elif intValue < 1:
                print("Value cannot be less than 1")
                continue
            elif intValue > 8192: 
                print("Value cannot be greater than 8192")
                continue
            else:
                return("Error")

如果您检查输入的intValuelog2是否是一个整数-

import math
if int(math.log2(intValue)) == math.log2(intValue):
    return("The value is equal to " + str(intValue) )
else:
    # print error...

例如,如果intValue为32,则得到True,但对于33,则得到False。你知道吗

此外,还可以检查math.log2(intValue)是否小于或等于13,以满足值在小于8192之间的其他约束。你知道吗

相关问题 更多 >