<code>y = √(x*x + 3*x - 500)</code>

问题描述 投票:0回答:2
x2=25

。 我试图使用异常处理,但这无济于事。 我现在尝试使用的代码给了我:

ValueError: math domain error
import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x*x + 3*x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))
输出应该像这样:
 x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14

平方根的论点一定不能为负。在这里使用异常处理非常好,请参见下文:

Playground:
Https://ideone.com/vmcewp

import math

x1 = int(input("Enter first number:\n"))
x2 = int(input("Enter second number:\n"))

print(" x\ty")
for x in range(x1, x2 + 1):
    try:
        formula = math.sqrt(x**2 + 3*x - 500)
        print("%d\t%.2f" % (x, formula))
    except ValueError:  # Square root of a negative number.
        print("%d\txxx" % x)
python math error-handling valueerror sqrt
2个回答
2
投票
资源:

wiki.python.org:处理异常

您必须检查表达式是否为the the the the Square root。否则,您将获得负数的SQRT,这给您带来了域错误。
    

< 0
  • 您应该尝试修改您的代码,如下所示。在执行import math x1 = int(input("Enter first number:")) x2 = int(input("Enter second number:")) print(" x", " y") for x in range(x1, x2+1): formula = x * x + 3 * x - 500 if formula < 0: print (x, "***") else: formula = math.sqrt(formula) print(x, round(formula, 2))
之前计算表达值

0
投票


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.