سؤال

I am currently working on a program in Python that will factor trinomial equations into binomial equations. However, the problem is that whenever I calculate the binomials, if it is positive then the + sign will not show up. For example, when I input 2 for b and -15 for c I get the output

The binomials are: (x-3)(x5)

As you can see, the + sign does not show for the second binomial. How can I fix this?

Here is my code:

import math
print " This program will find the binomials of an equation."
a = int(raw_input('Enter the first coefficient'))
b = int(raw_input('Enter the second coefficient'))
c = int(raw_input('Enter the third term'))
firstbinomial=str(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))
secondbinomial=str(int((((b*-1)-math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))  
print"The binomials are: (x"+firstbinomial+")(x"+secondbinomial")"

I have tried doing:

import math
    print " This program will find the binomials of an equation."
    a = int(raw_input('Enter the first coefficient'))
    b = int(raw_input('Enter the second coefficient'))
    c = int(raw_input('Enter the third term'))
    firstbinomial=str(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))
if firstbinomial<=0:
     sign=""
else:
     sign="+"
    secondbinomial=str(int((((b*-1)-math.sqrt((b**2)-(4*a*c)))/(2*a))*-1))  
if secondbinomial<=0:
     sign=""
else:
     sign="+"
    print"The binomials are: (x"+sign+firstbinomial+")(x"+sign+secondbinomial")"

However I ended up getting:

The binomials are: (x+-3)(x+5)

هل كانت مفيدة؟

المحلول

You need to use string formatting to show positive signs, or explicitly use + in the string:

firstbinomial =  (((b * -1) + math.sqrt((b ** 2) - (4 * a * c))) / (2 * a)) * -1
secondbinomial = (((b * -1) - math.sqrt((b ** 2) - (4 * a * c))) / (2 * a)) * -1

print "The binomials are: (x{:+.0f})(x{:+.0f})".format(firstbinomial, secondbinomial)

# prints "The binomials are: (x-3)(x+5)"

(which leaves the values as floats but formats without the decimal point), or

print "The binomials are: (x+{})(x+{})".format(firstbinomial, secondbinomial)

# prints "The binomials are: (x+-3)(x+5)"

The - only shows because negative values are always printed with their sign.

نصائح أخرى

You should use string formatting to produce your output. Numbers can be given the "+" formatting option to always show their signs, rather than only showing for negatives:

print "The binomials are: (x{:+})(x{:+})".format(firstbinomial, secondbinomial)

This requires that you skip calling str on the integer value you calculate for firstbinomial and secondbinomial on the previous lines.

If you needed the values (with their signs) as strings, an alternative might be to use the format function rather than str:

firstbinomial = format(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1), "+")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top