第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

牛頓近似平方根的方法

牛頓近似平方根的方法

繁華開滿天機(jī) 2021-12-09 10:47:03
我正在嘗試編寫一個(gè)函數(shù)來計(jì)算牛頓法。希望我的代碼中不斷出現(xiàn)錯(cuò)誤。這是給我寫代碼的提示這是我寫下的代碼import mathdef newton(x):   tolerance = 0.000001   estimate = 1.0   while True:        estimate = (estimate + x / estimate) / 2        difference = abs(x - estimate ** 2)        if difference <= tolerance:            break   return estimatedef 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))main()它似乎正在工作,但是當(dāng)我對(duì) Cengage 運(yùn)行檢查時(shí),我不斷收到此錯(cuò)誤我不太確定這意味著什么,因?yàn)槲业拇a似乎運(yùn)行得很好。誰能幫忙解釋一下?
查看完整描述

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 == ""。


查看完整回答
反對(duì) 回復(fù) 2021-12-09
?
倚天杖

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()


查看完整回答
反對(duì) 回復(fù) 2021-12-09
  • 2 回答
  • 0 關(guān)注
  • 246 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)