0

I just started coding for about a month now. I'm making my first actually useful program that finds the root/s of a quadratic equation. It's almost done and it needs a little bit more fixing but there's one thing I can't really seem to figure out. Here's my code:

import math
filler = "Empty Here"
print("Please enter in integer coefficients a, b, and c")
operator_for_bx = " + "
operator_for_c = " + "
a = int(input("a="))
b = int(input("b="))
c = int(input("c="))
discriminant = b*b - 4*a*c
determinant = discriminant
root_positive = str(float((-b + math.sqrt(discriminant)) / (2*a)))
root_negative = str(float((-b - math.sqrt(discriminant)) / (2*a)))
root_one_real_sol = str(float((-b)/(2*a)))

if b < 0:
    operator_for_bx = " - "
if c < 0:
    operator_for_c = " - "


if a == 1:
    print("Your quadratic equation is: " + "x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))
elif a == -1:
    print("Your quadratic equation is: " + "-x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))
else:
    print("Your quadratic equation is: " + str(a) + "x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))

if determinant == 0:
    print("It only has 1 real solution.")
    print("It's root is: " + root_one_real_sol + ".")
elif determinant >= 1:
    print("It has 2 real solutions.")
    print("The roots are: " + root_positive + " and " + root_negative + ".")
else:
    print("It has 2 complex but not real solutions.")

You see, occasionally the answer I get for the roots turns out into a whole number. Which is fine and all, but the thing is I had to let it out as a float or else decimal numbers wouldn't work. So if ever a whole number would appear, it'd say "x.0",(x being whatever number came out) and I don't want a decimal point to be shown if it's a whole number so, how do should I make it so? (Also yes I know this won't work for quadratic equations with 2 complex but not real solutions and I think I can fix that by myself- maybe I'll use the Try and Except stuff)

  • You could use something like [`sprintf`](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations)to format the output to a specific length of digits. However you're going to need to use a condition to remove the trailing decimal paces in the event thay it's 0. – Sherif Jul 18 '21 at 14:24

1 Answers1

2

Here's an example code that could accomplish that:

x = [1.0, 2.0, 2.5, 3.5]

new_x = [int(i) if int(i) == i else i for i in x]

print(new_x)

Output:

[1, 2, 2.5, 3.5]

This uses list comprehension, but the main idea I want to show is that in order to check if something has nothing after "." you can just check that the int version of it is equal to the floating point version.

A.M. Ducu
  • 892
  • 7
  • 19