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

2024-10-01 15:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

The binomials are: (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")"

我试过做:

^{pr2}$

但我最终得到:

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


Tags: theinputrawmathsqrtareint方程
2条回答

{1>要在字符串中显式使用“^”或“^”符号:

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

(将值保留为浮点数,但格式没有小数点),或

^{pr2}$

-只显示,因为负值总是用它们的符号打印。在

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

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

这要求您跳过对前面几行中为firstbinomial和{}计算的整数值调用str。在

如果需要将值(及其符号)作为字符串,另一种方法可能是使用format函数而不是str

^{pr2}$

相关问题 更多 >

    热门问题