簡體   English   中英

如何在Python中的負數之前添加括號

[英]how to add parentheses before a negative number in python

我已經建立了一個計算二次方程式並找到解決方案的項目。 我已經輸入了abc的值。 當我輸入值時,將出現完整的二次方程式。 例如,我輸入a:2b:3c:4 ,它顯示為2x2+3x+4 現在問題出在負數上。 如果我給b的值-3c的值-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))

您可以定義一個函數,如果number為負數,該函數將添加括號並使用它代替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))

如果您希望它更具可讀性,那么這是一種替代方法:

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

稍長一點,但打印效果不錯。

您可以以更好的方式利用Python的字符串格式,使用將整數n映射為str(n)如果為正數)或(-str(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

只需在第二個測試中為每個var和chnge +添加()到-,因為+與-=-

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM