2017-07-24 194 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

谢谢是的公式不正确! –