Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试使用while循环计算sqroot时出现代码问题_Python_Loops_While Loop - Fatal编程技术网

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**2
ans**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"""