Answer the question
In order to leave comments, you need to log in
How to beautifully print a quadratic equation to the console?
Wrote a simple code for solving quadratic equations. In the end, I decided to write the output of the final equation on the screen as a final touch before starting the solution, after a few minutes I realized that I did not understand how to implement it. First, the quadratic equation can be like this 2x^2+5x-4 or like this -2.1x^2-4.5x+8.3 (numbers in front of x can be both negative and positive, as well as fractional or integer). So, briefly the question is: how to make the output flexible and beautiful? I do not want to see, when entering only integer values, something like 2.0x^2+5.0x-4.0 = 0 and so on. Spoiler code.
import math
while True:
a = float(input('Введите a: '))
b = float(input('Введите b: '))
c = float(input('Введите c: '))
d = b ** 2 - 4 * a * c
print("\nВычисляем дискриминант...")
print("Дискриминант равняется", d)
if d == 0:
print("\nДискриминант равен 0")
print("x =", -b/(2*a))
elif d < 0:
print("\nДискриминант меньше 0, решений нет")
else:
x1 = (-b - math.sqrt(d)) / (2*a)
x2 = (-b + math.sqrt(d)) / (2*a)
print("\nВычисляем корни...")
print("\nПервый корень равен", x1)
print("Второй корень равен", x2)
while True:
print("\nХотите решить ещё одно уравнение?")
answer = input('Y/n(help - справка по командам) ')
if answer == 'Y':
break
elif answer == 'n':
exit()
elif answer == 'help':
print(open('help.txt', 'r').read())
else:
print("\nВведите Y или n (help - справка по командам)")
Answer the question
In order to leave comments, you need to log in
If you want to leave forced formatting in float, then you can do this:
def quadratic_eq_formatter(nums):
num_f = {1: '{:+.0f}', 0: '{:+.1f}'}
eq = '{}x^2{}x{}=0'.format(*(num_f[x.is_integer()] for x in nums))
return eq.format(*nums) if nums[0] < 0 else eq.format(*nums)[1:]
nums = (a, b, c)
print(quadratic_eq_formatter(nums))
print(quadratic_eq_formatter([-3.0, -2.7, 7.0]))
'-3x^2-2.7x+7=0'
print(quadratic_eq_formatter([2.0, 5.0, -4.0]))
'2x^2+5x-4=0'
print(quadratic_eq_formatter([-2.1, -4.5, 8.3]))
'-2.1x^2-4.5x+8.3=0'
print(quadratic_eq_formatter([-2.0, 5.0, 5.2]))
-2x²+5x+5.2=0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question