首页 > 解决方案 > 在python中检查差异数小于10或大于10

问题描述

如何查找一个数字是否小于或大于 10 的差异。

示例 1:如果 a 是 100,b 是 91。这几乎是匹配。

示例 2:如果 a 是 100,b 是 89。这根本不是匹配。

下面是代码及其工作正常。有没有其他最简单或最好的方法来实现

a = 110
b = 100
c = a - b
d = a - 10
if a > b:
    if (a - b) <= 10:
        print "This is almost Matching"
    else:
        print "This is not at Matching"
else:
    if (b - a) <= 10:
        print "This is almost Matching"
    else:
        print "This is not at Matching"

预期和实际变得相同

标签: python

解决方案


您需要寻找差异的绝对值(a,b)

该方法abs()返回 x 的绝对值 - x 和零之间的(正)距离。

a = 100
b = 110
print(abs(a - b))  # 10

if abs(a -b) <= 10:
    print("This is almost Matching")
else:
    print("This is not at Matching")

输出:

10
This is almost Matching

推荐阅读