尝试在main中调用一个函数但未获得2个输出

时间:2019-10-28 14:33:55

标签: python function math syntax-error

我有一个作业问题,将在下面显示,要求我在主函数中包装平方根函数。如果用户按下Enter键,它将退出循环,否则它将继续运行。我在这里遇到两个问题,第一个是,每当我运行它时,我总是会得到2个输出,这我知道为什么会出现,但似乎无法解决。第二个是我不知道如何让用户按下Enter键并退出程序,而不将所有内容都转换为字符串。

import math

def newton():
     x = float(input("Enter a positive number: "))

     tolerance = 0.000001
     estimate = 1.0

     while True:
          estimate = (estimate + x / estimate) / 2
          difference = abs(x - estimate ** 2)
          if difference <= tolerance:
              break

     print("The program's estimate is", estimate)
     print("Python's estimate is     ", math.sqrt(x))

def main():
     x = str(input("Enter a positive number: "))
     if x == '':
          return
     else:
          x = float(x)
          newton()
main()

这是错误的一个例子

Enter a positive number: 2
Enter a positive number: 2
The program's estimate is 1.4142135623746899
Python's estimate is      1.4142135623730951

2 个答案:

答案 0 :(得分:0)

def newton(x):
    tolerance = 0.000001
    estimate = 1.0

    while True:
        estimate = (estimate + x / estimate) / 2
        difference = abs(x - estimate ** 2)
        if difference <= tolerance:
            break

    print("The program's estimate is", estimate)
    print("Python's estimate is     ", math.sqrt(x))

 def main():
     x = str(input("Enter a positive number: "))
     if x == '':
         return
     else:
         x = float(x)
         newton(x)

尝试运行此程序。您必须将x传递到newton(x)

答案 1 :(得分:0)

您只需要输入一次,并将结果传递给牛顿函数。为了保持循环,我在main中添加了一个循环,该循环将不断要求输入。如果输入可以转换为浮点型,则将调用牛顿,否则将停止。

import math

def newton(number):
     tolerance = 0.000001
     estimate = 1.0

     while True:
          estimate = (estimate + number / estimate) / 2
          difference = abs(number - estimate ** 2)
          if difference <= tolerance:
              break

     print("The program's estimate is", estimate)
     print("Python's estimate is     ", math.sqrt(number))

def main():
    while True:
        x = str(input("Enter a positive number: "))
        try:
            x = float(x)
            newton(x)
        except ValueError as ve:
            break
main()
相关问题