0
我在Python 3.6.0上編寫了下面的代碼來找到Spyder編輯器上的立方體根。Python程序找到立方體根的溢出錯誤
#Finding the cube root
#import math
y=input("Enter a number whose cube root you want to find: ")
root=float(y)
#x1=math.pow(root,1/3)
n=input("Enter the degree of accuracy: ")
epsilon=float(n)
x1=root/3.0
while True:
if x1>root and abs(root-x1)<=epsilon:
break
else:
x1=1/3*(2*x1+root/(x1**2))
print("The cube root is", x1)
但是,輸出顯示 「溢出錯誤」 並且 「結果是大」。然後,我推出了以下打印聲明:
else:
print(x1)
x1=1/3*(2*x1+root/(x1**2))
現在我發現,中,環無限運行。 print聲明顯示已達到正確答案,但循環從未終止。
任何機構可以告訴我我犯了什麼錯誤,以及如何在不更改公式的情況下找到立方體根?
您的if語句打破循環的一部分是'X1> root'。如果'root'大於1,那麼'x1'永遠不會比這大。考慮一下,如果'root'是'8.0',你的算法應該集中在2.0的'x1'上,但是2.0> 8.0'永遠不會是真的,所以你的if語句永遠不會讓你進入'break'。 –