ValueError:二级方程式中的数学域错误

2024-07-01 06:59:00 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我为什么我会犯这个错误吗?你知道吗

Traceback (most recent call last):
  File "file.py", line 14, in <module>
    p2 = math.sqrt(b*b -4*a*c)
ValueError: math domain error

我是一个新手编码,所以需要一些帮助:)

我的代码如下所示:

# -*- coding: utf-8 -*-
a = input("¿Qué valor es a?")
while(str(a).isdigit() != True):
  a = input("Porfavor, introduce un número para a, no un texto")
b = input("¿Qué valor es b?")
while(str(b).isdigit() != True):
  b = input("Porfavor, introduce un número para b, no un texto")
c = input("¿Qué valor es c?")
while(str(c).isdigit() != True):
  c = input("Porfavor, introduce un número para c, no un texto")

import math
p1 = b * -1
p2 = math.sqrt(b*b -4*a*c)
p3 = 2*a
s1 = (p1+p2)/p3
s2 = (p1-p2)/p3
print("Soluciones :", s1, " y ", s2)

Tags: trueinputesmathvalorunp2para
2条回答

你必须这样做数学.sqrt不接受负值。如果b*b-4*a*c是一个负数,那么你会得到数学域错误。解决这个问题的一种方法是使用if语句预先检查sqrt操作中的值是否为负值。你知道吗

我想你不是在寻找假想的根 如果你是,你应该看看cmath

你应该把那个街区改成

try:
    p1 = b * -1
    math.sqrt(b**2 - 4*a*c)
    p3 = 2*a
    s1 = (p1+p2)/p3
    s2 = (p1-p2)/p3
    print("Soluciones :", s1, " y ", s2)
except ValueError:
    print("No real solution")

这称为异常处理,它是这种情况下的完美工具。它将转到except语句的唯一时间是数学.sqrt()为负数。在这种情况下,根是虚构的,所以打印(“没有真正的解决方案”)或任何你想要的错误信息!你知道吗

相关问题 更多 >

    热门问题