Лабы / ЛР1_доработка
.docximport sys
from math import sqrt
def real_roots(a, b, c):
try:
a, b, c = float(a), float(b), float(c)
except ValueError as e:
raise RuntimeError(f"Некорректный ввод: a = {a}, b = {b}, c = {c}") # Исключение
if a == 0:
try:
x1 = -c / b
return x1
except ZeroDivisionError as e:
raise ZeroDivisionError("Деление на ноль")
try:
discriminant = (b ** 2) - (4 * a * c)
except OverflowError as e: #вылетает именно тут при большом числе
raise OverflowError("Слишком большое число")
if discriminant < 0:
raise RuntimeError("Корней нет") # Исключение
if discriminant == 0:
x = -b / (2 * a)
return x
x1 = (-b + sqrt(discriminant)) / (2 * a)
x2 = (-b - sqrt(discriminant)) / (2 * a)
if float('-inf') < float(x1) < float('inf') and float('-inf') < float(x2) < float('inf'): #Нужно чтобы проверял на nan, inf, и если что-то не так обрабатывал исключение
return [x1, x2]
else:
raise RuntimeError(f"Некорректный ввод: a = {a}, b = {b}, c = {c}")
def main():
while True:
print("Введите коэффициенты для уравнения")
print("Ax^2 + Bx + C = 0:")
try:
a = input("a = ")
b = input("b = ")
c = input("c = ")
print(real_roots(a, b, c))
#действия в случае исключений:
except ValueError as e:
print(f"{str(e)}")
except RuntimeError as e:
print(f"{str(e)}")
except ZeroDivisionError as e:
print(f"{str(e)}")
except OverflowError as e:
print(f"{str(e)}")
except KeyboardInterrupt:
sys.exit()
if __name__ == "__main__":#Чтобы не было путаницы при запуске напрямую и при импорте
main()