Квадратичная формула Python, не рассчитанная точно - PullRequest
2 голосов
/ 07 апреля 2019

Это мой основной файл, который запускает программу:

import math
import Disc

def main():

    coeffA = int(input('Enter the coefficient A: '))
    coeffB = int(input('Enter the coefficient B: '))
    coeffC = int(input('Enter the coefficient C: '))

    disc = Disc.discriminant(coeffA, coeffB, coeffC)

    while coeffA != 0:


        if disc > 0:

            solutionOne = (-coeffB + math.sqrt(disc)) / (2 * coeffA)
            solutionTwo = (-coeffB - math.sqrt(disc)) / (2 * coeffA)

            print('Solutions are: ' + str(solutionOne) + ' and ' + str(solutionTwo))

            coeffA = int(input('Enter the coefficient A: '))
            coeffB = int(input('Enter the coefficient B: '))
            coeffC = int(input('Enter the coefficient C: '))

        elif disc == 0:

            solutionOne = -coeffB / (2 * coeffA)

            print('Solution is: ' + str(solutionOne))

            coeffA = int(input('Enter the coefficient A: '))
            coeffB = int(input('Enter the coefficient B: '))
            coeffC = int(input('Enter the coefficient C: '))

        elif disc < 0:

            print('Equation has two complex roots.')

            coeffA = int(input('Enter the coefficient A: '))
            coeffB = int(input('Enter the coefficient B: '))
            coeffC = int(input('Enter the coefficient C: '))

    else:
        print('Program ended.')


# End of the main function

main()

Вот файл Disc.py, где вычисляется значение дискриминанта для использования в функции main ():

def discriminant(coeffA, coeffB, coeffC):

    value = (coeffB ** 2) - (4 * coeffA * coeffC)

    return value

Это вывод при запуске программы:

Enter the coefficient A: 1
Enter the coefficient B: 2
Enter the coefficient C: -8
Solutions are: 2.0 and -4.0
Enter the coefficient A: 1
Enter the coefficient B: -12
Enter the coefficient C: 36
Solutions are: 9.0 and 3.0
Enter the coefficient A: 2
Enter the coefficient B: 9
Enter the coefficient C: -5
Solutions are: -0.75 and -3.75
Enter the coefficient A: 4
Enter the coefficient B: 6
Enter the coefficient C: 20
Solutions are: 0.0 and -1.5
Enter the coefficient A: 0
Enter the coefficient B: 0
Enter the coefficient C: 0
Program ended.

Я ожидаю следующих корней с данными выше:

Run1: 2, -4

Run2: 6

Run3: .5, -5

Run4: 'Equation has two complex roots.'

Когда я запускаю программу, выходные данные являются неправильными в течение последних 3 раз, когда программа запускается, и, кажется, устанавливает дискриминант равным значениям больше 0, когда я ожидаю, что он изменит выход на основе вычисленного дискриминанта. Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 08 апреля 2019

Нашел решение.Моя дискриминантная функция была за пределами оператора while, поэтому, когда 3 переменные были введены пользователем, она сохраняла первый дискриминант, рассчитанный в каждом цикле, поэтому выход производил 2 ответа при каждом запуске.Изменяя положение дискриминантной функции внутри оператора while, теперь он пересчитывает дискриминант для каждого цикла для оператора while.Это правильный код для этой проблемы:

import math
import Disc

def main():



    coeffA = int(input('Enter the coefficient A: '))

    while coeffA != 0:

        coeffB = int(input('Enter the coefficient B: '))
        coeffC = int(input('Enter the coefficient C: '))

        disc = Disc.discriminant(coeffA, coeffB, coeffC)

        if disc > 0:

            solutionOne = (-coeffB + math.sqrt(disc)) / (2 * coeffA)
            solutionTwo = (-coeffB - math.sqrt(disc)) / (2 * coeffA)

            print('Solutions are: ' + str(solutionOne) + ' and ' + str(solutionTwo))

            coeffA = int(input('Enter the coefficient A: '))

        elif disc == 0:

            solutionOne = -coeffB / (2 * coeffA)

            print('Solution is: ' + str(solutionOne))

            coeffA = int(input('Enter the coefficient A: '))

        elif disc < 0:

            print('Equation has two complex roots.')

            coeffA = int(input('Enter the coefficient A: '))

    print('Program ended.')


    # End of the main function

Правильный код вывода:

Enter the coefficient A: 1
Enter the coefficient B: 2
Enter the coefficient C: -8
Solutions are: 2.0 and -4.0
Enter the coefficient A: 1
Enter the coefficient B: -12
Enter the coefficient C: 36
Solution is: 6.0
Enter the coefficient A: 2
Enter the coefficient B: 9
Enter the coefficient C: -5
Solutions are: 0.5 and -5.0
Enter the coefficient A: 4
Enter the coefficient B: 6
Enter the coefficient C: 20
Equation has two complex roots.
Enter the coefficient A: 0
Program ended.

Спасибо за всю помощь и советы от сообщества переполнения стека!

0 голосов
/ 07 апреля 2019

Кажется, вам не хватает пары скобок.Это должно исправить ошибки:

if disc > 0:

            solutionOne = (-coeffB + math.sqrt(disc)) / (2 * coeffA)
            solutionTwo = (-coeffB - math.sqrt(disc)) / (2 * coeffA)

            print('Solutions are: ' + str(solutionOne) + ' and ' + str(solutionTwo))

            coeffA = int(input('Enter the coefficient A: '))
            coeffB = int(input('Enter the coefficient B: '))
            coeffC = int(input('Enter the coefficient C: '))
...