2 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
當(dāng)輸入為空時(shí),似乎會(huì)出現(xiàn)此問題。一個(gè)潛在的解決方法,假設(shè)您只想要正數(shù)作為輸入,將設(shè)置一個(gè)負(fù)數(shù)(或您選擇的任何其他內(nèi)容),例如 -1,作為退出條件:
x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
這應(yīng)該避免EOFError.
編輯
如果您想使用空白輸入(點(diǎn)擊返回行)來跳出循環(huán),您可以嘗試以下替代語法:
x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
該not x檢查是否x為空。這也更符合Python比x == ""。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
我是這樣做的,Cengage 接受了。
import math
tolerance = 0.000001
def newton(x):
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
def main():
while True:
x = input("Enter a positive number or enter/return to quit: ")
if x == "":
break
x = float(x)
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
if __name__ == "__main__":
main()
添加回答
舉報(bào)