Python完美平方数检测程序误判144,求错误原因排查
问题分析
你的代码核心错误在于:
- 使用
x ** 0.5计算平方根时,无论结果是否为整数,返回的都是浮点数类型。比如144的平方根是12.0,它是float而不是int,所以isinstance(b, int)永远返回False,导致程序误判。
修正方案
可以通过两种可靠方式解决:
方案1:验证浮点数整数性+反向校验(避免精度误差)
先判断平方根的浮点数是否等于其整数形式,再计算该整数的平方是否等于原数(防止浮点数精度带来的误差,比如25.000000000000004这类情况)。
修正代码:
def is_perfect_square(): x = int(input("Enter a number:")) sqrt_x = x ** 0.5 if sqrt_x == int(sqrt_x) and int(sqrt_x) ** 2 == x: print("It is a perfect square") else: print("It is not a perfect square") is_perfect_square()
方案2:纯整数运算(更稳定)
使用Python 3.8+自带的math.isqrt函数,它返回原数的整数平方根(向下取整),再判断该整数的平方是否等于原数:
import math def is_perfect_square(): x = int(input("Enter a number:")) sqrt_x = math.isqrt(x) if sqrt_x ** 2 == x: print("It is a perfect square") else: print("It is not a perfect square") is_perfect_square()
内容的提问来源于stack exchange,提问作者siddhantuniyal
相关产品推荐
相关产品推荐

