繁体   English   中英

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

[英]How to make the plus sign show for a variable in python

我目前正在使用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)

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

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

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

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

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

这要求您跳过在前几行中为firstbinomialsecondbinomial计算的整数值上调用str的过程。

如果您需要将值(带有符号)作为字符串,则替代方法是使用format函数而不是str

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM