巴比伦方法求解数字的平方根

问题描述 投票:0回答:1

因此,我必须编写一个程序以使用巴比伦方法来计算一组范围的平方根。但是,我很困惑,因为我编写的程序只给了我一个数字的平方根。我为测试输入的范围是1、16。但是我只得到15的平方根。

图片是程序应显示的内容。Program output

question1 = input("Enter 'single' or 'range' to solve for a single square root or a range of values, respectively: ")
if question1 == "single":
    value1 = int(input("Please enter a positive integer above 0: "))
    if value1 <= 0:
        print("Please enter an positive integer above 0: ")
        value1 = int(input("Please enter a positive integer above 0: "))

    oValue = 1
    value2 = value1
    e = 0.0001
    while value2 - oValue > e:
        value2 = (value2 + oValue) / 2
        oValue = value1 / value2

    print(format(oValue, ".3f"))

else:
    start = int(input("Enter a positive integer value to start your range: "))
    end = int(input("Enter a positive integer value to end your range: "))
    for num in range(start, end):
        oValue = 1
        value2 = num
        e = 0.0001
        while value2 - oValue > e:
            value2 = (value2 + oValue) / 2
            oValue = num / value2

print(format(oValue, ".3f"))

因此,我必须编写一个程序以使用巴比伦方法来计算一组范围的平方根。但是,我被困住了,因为我编写的程序只给了我......>

python square-root
1个回答
0
投票

您很近。最后一行需要缩进更多:

...
else:
    start = int(input("Enter a positive integer value to start your range: "))
    end = int(input("Enter a positive integer value to end your range: "))
    for num in range(start, end):
        oValue = 1
        value2 = num
        e = 0.0001
        while value2 - oValue > e:
            value2 = (value2 + oValue) / 2
            oValue = num / value2
        print(format(oValue, ".3f"))
© www.soinside.com 2019 - 2024. All rights reserved.