2017-07-24 195 views
-3

我真的很新的python。我試圖讓這個工作。for循環,如果語句

import math 
number, times = eval(input('Hello please enter the value and number of times to improve the guess followed by comma:')) 
guess=number/2 
sq_math= math.sqrt(number) 
if times>1: 
    for i in range(2,times+1): 
     guess=(guess+times/guess)/2 
     if round(guess,1) == round(sq_math,1): 
     break 

else: 
    pass 

print('Newtons method guessed {0}, square root was {1}'.format(guess, sq_math)) 

那麼他最好的辦法是什麼?感謝你們!

+1

嗨,歡迎來到堆棧溢出。請回顧[問]並幫助我們解釋您想要發生的事情,您遇到的錯誤以及您不瞭解的內容。 –

+1

它是做什麼的?它應該做什麼?任何錯誤?你期望輸出什麼?你會得到什麼輸出? – jacoblaw

+1

請不要這樣做:'number,times = eval(input(...))' –

回答

1

你想要做的布爾值不等於比較round(guess,1) != round(sq_math,1)在一個單獨的if條款,就像你已爲相等比較==完成:

if times>1: 
    # break this next line up in to two lines, `for` and `if` 
    # for i in range(2,times+1) and round(guess,1) != round(sq_math,1): 
    for i in range(2,times+1):     # for check 
     if round(guess,1) != round(sq_math,1): # if check 
      guess=(guess+times/guess)/2 
     if round(guess,1) == round(sq_math,1): 
      break 
     times-=1 #decrement times until we reach 0 

演示:

Hello please enter the value and number of times to improve the guess followed by comma:9,56 
Newtons method guessed 3.0043528214, square root was 3.0 
+0

「您好,請輸入值和次數以改善猜測,然後加上逗號:9,56 牛頓方法猜測7.483314773547883,平方根3.0「由於某種原因,它不想給我正確的答案。 –

+0

對不起,我不知道正確的答案是什麼。你想得到什麼正確的答案? https://stackoverflow.com/questions/45291577/for-loop-if-statement/45292363?noredirect=1#comment77545467_45291577 – davedwards

+0

你可以在公式中看到。當round(猜測)將是3時,它應該打破並打印猜測。 –

0

我相信主要問題是這個公式不正確:

guess = (guess + times/guess)/2 

它應該是:

guess = (guess + number/guess)/2 

我看不出有任何問題與您if聲明也不是你for循環。完整的解決方案:

import math 

number = int(input('Please enter the value: ')) 
times = int(input('Please enter the number of times to improve the guess: ')) 

answer = math.sqrt(number) 

guess = number/2 

if times > 1: 
    for _ in range(times - 1): 
     guess = (guess + number/guess)/2 
     if round(guess, 1) == round(answer, 1): 
      break 

print("Newton's method guessed {0}; square root was {1}".format(guess, answer)) 

用法

% python3 test.py 
Please enter the value: 169 
Please enter the number of times to improve the guess: 6 
Newton's method guessed 13.001272448567825; square root was 13.0 
% 

雖然我相信我真的實施尋找平方根巴比倫的方法。

+0

謝謝是的公式不正確! –