Python 尝试使用while循环计算sqroot时出现代码问题
我试着用循环来计算平方根。 我不确定我的代码出了什么问题,因为它无法识别正确的答案Python 尝试使用while循环计算sqroot时出现代码问题,python,loops,while-loop,Python,Loops,While Loop,我试着用循环来计算平方根。 我不确定我的代码出了什么问题,因为它无法识别正确的答案 x = 25.0 ans = 0.0 while ans**2 <= x: ans += 0.5 if ans**2 == x: print ans print ans**2 else: print "no square root" print ans print ans**2 不,这不是家庭作业,我是32岁的老学员 编辑 谢谢大家的回答。我稍微修改了
x = 25.0
ans = 0.0
while ans**2 <= x:
ans += 0.5
if ans**2 == x:
print ans
print ans**2
else:
print "no square root"
print ans
print ans**2
不,这不是家庭作业,我是32岁的老学员
编辑
谢谢大家的回答。我稍微修改了一段代码,修改了while循环和if语句,现在我的代码如下所示
x = 25.0
ans = 0.0
while ans**2 < x:
ans += 0.2
if ans**2 != x:
print "root not found"
print ans
print ans**2
else:
print "found square root"
print ans
print ans**2
Im puzzeld如果ans**2==x,则行
将永远不会为真,因为前面的循环而ans**2算法的问题很简单,在行而ans**2ans**2重复?压痕问题。将if/else放在循环中。在实际尝试任何数字之前,先运行所有要尝试的数字(执行整个while循环)!呃,不,他没有。这是一个非常近似的平方根算法。要自己调试它,您可以添加一些打印语句,例如在递增ans后的while循环中,您可以将其打印出来,然后您会看到ans递增到5.0以上
x = 25.0
ans = 0.0
while ans**2 < x:
ans += 0.2
if ans**2 != x:
print "root not found"
print ans
print ans**2
else:
print "found square root"
print ans
print ans**2
root not found
5.0
25.0
precision = 0.0001
if math.fabs(ans**2 - x) <= precision:
"""then they are close enough for our purposes"""