3

Начал изучать питон, начал с программы которая решает квадратное уравнение:

a = float(input("Input A variable: "))
b = float(input("Input B variable: "))
c = float(input("Input C variable: "))

if a != 0 :
    if b != 0 and c != 0:
        if b > 0 and c > 0:            
            print ("Eqation: ", a, "x^2 + ", b, "x +", c, " = 0")

        print ("Decide through discriminant: ")
        print ("D = b^2 - 4ac")
        print ("D = ",b,"^2 - 4","*",a,"*",c," = ",(b**2)," + ",(4*a*c)," = ",(b**2 - (4*a*c)))

        discr = (b**2 - (4*a*c))

        print ("Current value discreminant:", discr)

        if discr > 0:
            b1 = ('-'+ b)
            b1 = float(b)
            x1 = ((b1 + squrt(discr))/(2*a))
            print("x1 = ", x1)
            x2 = ((b1 - squrt(discr))/(2*a))
            print(x2)

        if discr == 0:
            x = float('-'+((b)/(2*a))

        if discr < 0:
            print ("there are no roots on the set of real numbers")

else:
    print("err: A variable not equals 0!")

Вначале она берет значения с клавиатуры:

a = float(input("Input A variable: "))
b = float(input("Input B variable: "))
c = float(input("Input C variable: "))

Дальше идут проверки на то не равна ли переменная А нулю, является ли это полным квадратным уравнением:

if a != 0 :
    if b != 0 and c != 0:
        if b > 0 and c > 0:

Последнее условное выражение выше будет использоваться для того что-бы в последующем вывести выражение на экран:

print ("Eqation: ", a, "x^2 +", b, "x +", c, " = 0")

Потом подробно по действиям расписывает нахождение дискриминанта и находит его:

print ("Eqation: ", a, "x^2 + ", b, "x +", c, " = 0")
print ("Decide through discriminant: ")
print ("D = b^2 - 4ac")
print ("D = ",b,"^2 - 4","*",a,"*",c," = ",(b**2)," + ",(4*a*c)," = ",(b**2 - (4*a*c)))

discr = (b**2 - (4*a*c))

print ("Current value discreminant:", discr)

Далее извлекает корни:

if discr > 0:
    b1 = ('-'+ b)
    b1 = float(b)
    x1 = ((b1 + squrt(discr))/(2*a))
    print("x1 = ", x1)
    x2 = ((b1 - squrt(discr))/(2*a))
    print(x2)

if discr == 0:
    x = float('-'+((b)/(2*a))

if discr < 0:
    print ("there are no roots on the set of real numbers")

И вот я подхожу к сути вопроса:

if discr < 0:
    print("there are no roots on the set of real numbers")

При запуске консоль выдаёт ошибку, как я понимаю она ссылается на код выше, сообщение выглядит так:

File "QuadEq.py", line 39 if discr < 0: ^ SyntaxError: invalid syntax

В чем может быть проблема?

P.S. скрипт запускаю на Linux сервере

4
  • 7
    x = float('-'+((b)/(2*a)) скобки не сбалансированы:( Нужна еще одна закрывающая. Или может лучше так x = -b/(2*a)?
    – mrEvgenX
    27 фев 2020 в 8:08
  • 4
    О, отлично заданый толковый вопрос. Плюс от меня. PS. Потом еще будет ошибка в строчке b1 = ('-'+ b), потому что складывать символы и числа нельзя. Можно решить так b1 = ('-'+ str(b)) 27 фев 2020 в 8:35
  • да, и так-же я забыл импортировать модуль math, спасибо, что помогли) 27 фев 2020 в 8:59
  • То самое чувство, когда у тебя в коде другие нашли больше ошибок, чем ты
    – alex9127
    20 мар 2020 в 19:43

2 ответа 2

1
if discr > 0:
            b1 = ('-'+ b)
            b1 = float(b)
            x1 = ((b1 + squrt(discr))/(2*a))
            print("x1 = ", x1)
            x2 = ((b1 - squrt(discr))/(2*a))
            print(x2)

Не "squrt", а "sqrt". И не был импортирован модуль "math".

0

вот я переписал твой код вроде должен работать

from math import sqrt
a = float(input("Input A variable: "))
b = float(input("Input B variable: "))
c = float(input("Input C variable: "))

if a != 0 and b !=0 and c != 0:

    if b > 0 and c > 0:            
        print (f"Eqation: {a}x^2 + {b}x + {c} = 0")

    print ("Decide through discriminant: ")
    print ("D = b^2 - 4ac")
    print (f"D = {b} ^ 2 - 4 * {a} * {c} = {b**2} + {(4*a*c)} = { (b**2) - (4*a*c) }")

    discr = (b**2 - (4*a*c))

    print ("Current value discreminant:", discr)

    if discr > 0:
        b1 = ('-'+ b)
        b1 = float(b)
        x1 = ((b1 + sqrt(discr))/(2*a))
        print("x1 = ", x1)
        x2 = ((b1 - sqrt(discr))/(2*a))
        print(x2)
    elif discr == 0:
        x = float(-b)/(2*a)
    else:
        print ("there are no roots on the set of real numbers")

else:
    print("err: A variable not equals 0!")

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.