You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:54:14