我正在嘗試做這個任務:創建一個程式,quadratic.py,它接受三個引數,代表二次公式中的 a、b 和 c 值。這些值應保留兩位小數。您不需要考慮虛數值。然后以以下形式列印出兩個根:“The solution are x and y” 其中 x 和 y 分別對應于正根和負根。
到目前為止,我有這個代碼:
import sys
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
discriminant = b**2 - 4*a*c
x1 = (-b discriminant**0.5) / (2*a)
x2 = (-b - discriminant**0.5) / (2*a)
xx1 = format(x1, '.2f')
xx2 = format(x2, '.2f')
print(f"Solutions: {xx1} and {xx2}")
我不明白為什么它不四舍五入我的 xx1 和 xx2 兩位小數
uj5u.com熱心網友回復:
請看一下“round”函式。也許它是“格式”方式的更簡單替代方法。
https://docs.python.org/3/library/functions.html?highlight=round#round
我希望它的結果有用。
uj5u.com熱心網友回復:
您可以使用round(value, digits). 所以在你的例子中,這將是:
xx1 = round(x1, 2)
xx2 = round(x2, 2)
編輯:
或者,在最后列印值時可以使用格式字串。
print(f"Solutions: {x1:.2f} and {x2:.2f}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374974.html
標籤:Python
