[英]Python Writing Quadratic Formula
我想嘗試讓我的打印功能自動替換變量'a''b'和'c',其中一個值分配給我的測試中的那些變量。 我該怎么做? 我理想的輸出看起來像這個等式:1x ** 2 + 4x + 4一個根。 2.0
import math
def quadraticRoots(a,b,c):
print('Equation: ax**2 + bx + c') # (this is what I am trying and it doesn't work)
discriminant = b**2 - 4 * a * c
if discriminant > 0:
root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a)
root2 = float(-b - math.sqrt(b**2 - 4 * a * c))/ (2 * a)
print('Two roots.')
print(root1)
print(root2)
elif discriminant == 0:
root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a)
print('One root.')
print(root1)
elif discriminant < 0:
print('No roots.')
def test():
quadraticRoots(1,0,0)
quadraticRoots(2,-11,-21)
quadraticRoots(4,1,4)
quadraticRoots(1,2,8)
quadraticRoots(3,-11,19)
quadraticRoots(1,4,4)
quadraticRoots(16,-11,64)
quadraticRoots(1,18,81)
quadraticRoots(1,7,42)
quadraticRoots(5,10,5)
test()
請嘗試以下方法:
print('Equation: {0}x**2 + {1}x + {2}'.format(a,b,c))
你在說那個嗎?
print('Equation: ax**2 + bx + c')
不會打印帶有a,b和c值的等式
print ('equation: ' + str(a) + 'x**2 + ' + str(b) + 'x + ' + str(c))
問題是你要求它打印一個文字,但你希望它根據你的值打印。 CAVEAT我認為你必須使用3+風格的python,我在2.7工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.