如何修复平方根的“ valueerror:数学域错误”? 我正在尝试编写一个计算公式y =√(x*x + 3*x -500)的程序, 间隔为[x1; x2]和f.e x1 = 15,x2 = 25。 我试图使用异常处理,但没有帮助。 和我尝试的代码...

问题描述 投票:0回答:3
和f.e

x1=15

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
python math error-handling valueerror sqrt
3个回答
2
投票
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)

资源: wiki.python.org:处理异常


    

您必须检查表达式是否为the the the the Square root。否则,您将获得负数的SQRT,这给您带来了域错误。
  • 您应该尝试修改您的代码,如下所示。在执行< 0
  • 之前计算表达值
sqrt

1
投票
print(" x", " y") for x in range(x1, x2): expres = x*x + 3*x - 500 if expres >= 0: formula = math.sqrt(expres) print(x, round(formula, 2)) else: print(x, "***")


 x  y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.0
22 7.07
23 9.9
24 12.17  
25 14.14

    


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