我试着找出最大的立方根它是一个整数,小于12000。

processing = True
n = 12000
while processing:
    n -= 1
    if n ** (1/3) == #checks to see if this has decimals or not

我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?


当前回答

你可以用这个:

if k == int(k):
    print(str(k) + " is a whole number!")

其他回答

你不需要循环或检查任何东西。只要取12000的立方根,四舍五入:

r = int(12000**(1/3.0))
print r*r*r # 10648

我们可以使用模(%)运算符。它告诉我们当x除以y时有多少余数-表示为x % y。每个整数都必须除以1,所以如果有余数,它一定不是整数。

这个函数将返回一个布尔值,True或False,取决于n是否为整数。

def is_whole(n):
    return n % 1 == 0

所有的答案都很好,但一个肯定的方法是

def whole (n):
     return (n*10)%10==0

如果是整数,函数返回True,否则返回False....我知道我有点晚了,但这是我做的一个有趣的方法。

编辑:正如下面的评论所述,一个更便宜的等效测试将是:

def whole(n):
    return n%1==0

这个问题已经解决了,但我想为函数提出一个额外的基于数学的解决方案。

这种方法的好处是,它计算你的数字的整数部分,这可能是有益的,取决于你的一般任务。

算法:

将整数分解为小数的和(例如,327=3*100+2*10+7*1) 取计算出的整数与数字本身的差值 判断差异是否足够接近,可以被认为是整数。

from math import ceil, log, isclose

def is_whole(x: float) -> bool:
    n_digits = ceil(log(x,10)) # number of digits of decimals at or above ones
    digits = [(n//(10**i))%10 for i in range(n_digits)] # parse digits of `x` at or above ones decimal
    whole = 0 # will equal the whole number part of `x`
    for i in range(n_digits):
        decimal = 10**i
        digit = digits[i]
        whole += digit*decimal
    
    diff = whole - x
    return isclose(diff, 0.0)

注意:解析数字的数字的思想就是从这里实现的

>>> def is_near_integer(n, precision=8, get_integer=False):
...     if get_integer:
...         return int(round(n, precision))
...     else:
...         return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
...     print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>