for循环,if语句

时间:2017-07-24 23:24:03

标签: python for-loop if-statement

我对python真的很陌生。我正试图让这个工作。

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

那么他最好的方式是什么?谢谢你们!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

USAGE

% 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
% 

虽然我相信我真的在实施巴比伦方法来寻找平方根。