Py学习  »  Python

python中如何在负数前加括号

Rino Sula • 5 年前 • 1734 次点击  

我已经建立了一个计算二次方程并找到解决方案的项目。我已经输入了 a , b c . 当我输入这些值时,就会出现完整的二次方程。例如我输入 a:2 , b:3 , c:4 ,看起来 2x2+3x+4 . 现在的问题是负数。如果我给 价值 -3 c类 价值 -4 ,二次方程如下: 2x2+-3x+-4 . 现在我希望它以这种形式出现: 2x2+(-3)x+(-4) . 有人能帮忙吗?

这是我的代码:

a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=int(input("Enter the value of c:"))
d = b**2-(4*a*c)
if b>0 and c>0:
    print("The quadratic equation is : " + str(a) + "x2+" + str(b) + "x+" + str(c))
elif b<0 and c<0:
    print("The quadratic equation is : " + str.format(a) + "x2+" + str(b) + "x+" + str(c))
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50900
 
1734 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Ayoub Benayache
Reply   •   1 楼
Ayoub Benayache    5 年前

只需在第二个测试中为每个var和chnge+to-添加()就可以了,因为+with-=-

a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=int(input("Enter the value of c:"))
d = (b)**2-(4*(a)*(c))
if b>0 and c>0:
    print("The quadratic equation is : " + str(a) + "x2+" + str(b) + "x+" + str(c))
elif b<0 and c<0:
    print("The quadratic equation is : " + str.format(a) + "x2" + str(b) + "x" + str(c))
MrGeek
Reply   •   2 楼
MrGeek    5 年前

可以更好地利用Python的字符串格式,使用映射整数的函数 n str(n) 如果是肯定的,或者 (-str(n)) 如果是阴性的:

def f(n):
    return str(n) if n >= 0 else '(%d)' % n

print("The quadratic equation is : {0}x2+{1}x+{2}".format(f(a), f(b), f(c)))

我建议一种更好的格式是实际放置数字的符号,而不是静态的 + 在操作数之间,并避免使用括号:

def f(n):
    return ('+' if n >= 0 else '-') + '%d' % abs(n)

eq_f = '{0}x2{1}x{2}'

print("The quadratic equation is : " + eq_f.format(f(a), f(b), f(c)))

输出(示例):

Enter the value of a:-1
Enter the value of b:5
Enter the value of c:-4
The quadratic equation is : -1x2+5x-4
L. B.
Reply   •   3 楼
L. B.    5 年前

如果你想让它更具可读性,这是另一种选择:

def beauty(coeff, i):

    if(coeff == 0): return ''

    if(i == 2):

        if(coeff ==  1): return  "x\u00B2"
        if(coeff == -1): return "-x\u00B2"
        return f"{coeff}x\u00B2"

    if(i == 1):

        if(coeff ==  1): return "+x"
        if(coeff == -1): return "-x"
        if(coeff  >  0): return f"+{coeff}x"
        return f"{coeff}x"

    if(i == 0):

        if(coeff >  0): return f"+{coeff}"
        return f"{coeff}"


def PrintQuadratic():

    a = int(input('a: '))
    b = int(input('b: '))
    c = int(input('c: '))

    print(f"{beauty(a,2)}{beauty(b,1)}{beauty(c,0)}")

PrintQuadratic()
a: 7
b: 9
c: 13
→ 7x²+9x+13

PrintQuadratic()
a: -1
b:  1
c:  0
→ -x²+x

PrintQuadratic()
a: 4
b: -2
c: 1
→ 4x²-2x+1

它有点长,但能产生很好的指纹。

Olvin Roght
Reply   •   4 楼
Olvin Roght    5 年前

您可以定义函数,如果数字为负数,则该函数将添加括号,并使用它代替 str() :

def fmt_num(x):
    return str(x) if x >= 0 else "({})".format(x)

...

print("The quadratic equation is : " + fmt_num(a) + "x2+" + fmt_num(b) + "x+" + fmt_num(c))