【发布时间】:2017-04-13 22:29:54
【问题描述】:
谁能告诉我为什么会出现这个错误?
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)
【问题讨论】:
-
math.sqrt不处理负值... -
您确定执行时输入的参数 a、b 和 c 是有效解吗?如果
4*a*c > b*b二次方程没有解。您应该添加IF(4*a*c>b*b): print("No solutions") else: ...的支票 -
@trashy 确定有解决方案,如果您的域是复数。
-
@juanpa.arrivillaga 在整篇文章中都没有提到使用复数。当然,您可以将 cmath 用于复杂的 sqrt 函数,然后找到两个虚根。但我不认为这就是问题所在。 (或者对正常的sqrt使用负值并手动添加i和-i)
-
@trashy 我唯一的一点是需要更好地说明问题。
标签: python