【发布时间】:2020-02-24 04:41:36
【问题描述】:
对于我的程序,我必须输入一个正数,但如果我输入一个负数,我需要程序出错并显示一条消息,“请使用正数并重试”,然后返回到您输入的部分输入一个数字。它陷入了一个循环。这是我的代码:
import math
# Receive the input number from the user
x = float(input("Enter a positive number: "))
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
#Perform the successive approximations
while True:
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
if diference <= tolerance:
break
elif x < 0:
print("Please enter a positive number")
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate: ", math.sqrt(x))
【问题讨论】:
-
您的问题已被编辑,以消除您对缺乏经验的歉意;不要认为这意味着人们不在乎,只是在公共问答论坛中,那些追随者更容易阅读不包含这些内容的问题。此外,这里欢迎所有技能水平;你不需要证明你的问题。 :)