python - 你如何检查一个数字是否可以被另一个数字整除?

我需要测试从 1 到 1000 的每个数字是 3 的倍数还是 5 的倍数。

我在 Python 2.x 中尝试过这段代码:

n = 0
s = 0

while (n < 1001):
    x = n/3
    if isinstance(x, (int, long)):
        print 'Multiple of 3!'
        s = s + n
    if False:
        y = n/5
        if isinstance(y, (int, long)):
            s = s + n

    print 'Number: '
    print n
    print 'Sum:'
    print s
    n = n + 1

想法是尝试将数字相除,看看结果是否为整数。但是,我没有得到预期的结果。

如何检验数字是否为整数?


在 2.x 中,这样的除法将产生一个整数,丢弃余数;见 How can I force division to be floating point? Division keeps rounding down to 0?了解详情。

在3.x中,除法会产生一个浮点值;结果不是“整数”即使是整数,所以isinstance检查会失败。见 Why does integer division yield a float instead of another integer?了解详情。

如果您需要整数除法的余数,而不是仅仅测试可除性,请参阅 Find the division remainder of a number .

最佳答案

您可以使用模数运算符 %

n % k == 0

当且仅当 nk 的精确倍数时才计算为真。在初等数学中,这称为除法的余数。

在您当前的方法中,您执行除法,结果将是

  • 如果您使用整数除法,则始终为整数,或者
  • 如果您使用浮点除法,则始终为 float 。

这是测试可分性的错误方法。

https://stackoverflow.com/questions/8002217/

相关文章:

python - SQLAlchemy:如何过滤日期字段?

python - sqlite3.ProgrammingError : You must not u

python - 在系统范围内安装 pip 和 virtualenv 的官方 "preferred"

python - 向 Pandas 数据框插入一行

python - 断言 numpy.array 相等性的最佳方法?

python - 在 TensorFlow 中使用预训练的词嵌入(word2vec 或 Glove)

python - 如何从具有透明背景的 matplotlib 导出绘图?

python - 有效地检查 Python/numpy/pandas 中的任意对象是否为 NaN?

python - 管道子流程标准输出到变量

python - matplotlib 中的曲面图