如何在python中为变量显示加号

时间:2013-11-09 00:46:33

标签: python python-2.7 binomial-coefficients

我目前正在研究Python中的程序,它将三项式方程式分解为二项式方程式。然而,问题是每当我计算二项式时,如果它是正数,那么+符号就不会出现。例如,当我为b输入2和为c输入-15时,我得到输出

  

二项式是:(x-3)(x5)

如您所见,+符号未显示第二个二项式。我该如何解决这个问题?

这是我的代码:

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")"

我尝试过:

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")"

然而我最终得到了:

  

二项式是:(x + -3)(x + 5)

2 个答案:

答案 0 :(得分:6)

您需要使用字符串格式显示正号,或在字符串中明确使用+

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)"

(将值保留为浮点数但格式不带小数点)或

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

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

-仅显示,因为负值始终以其符号打印。

答案 1 :(得分:3)

您应该使用字符串格式来生成输出。可以为数字提供"+"格式选项以始终显示其符号,而不是仅显示否定关键字:

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

这要求您跳过对前一行strfirstbinomial计算的整数值的secondbinomial

如果您需要将值(带有符号)作为字符串,则可以选择使用format函数而不是str

firstbinomial = format(int((((b*-1)+math.sqrt((b**2)-(4*a*c)))/(2*a))*-1), "+")