Python编写二次型

2024-09-30 10:39:17 发布

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

我想让我的print函数自动用测试中分配给这些变量的值之一替换变量“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()

Tags: 函数testdefmathsqrtfloat公式print
2条回答

尝试以下操作:

print('Equation: {0}x**2 + {1}x + {2}'.format(a,b,c))

你在说吗

 print('Equation: ax**2 + bx + c')   

不打印带有a、b和c值的公式

^{pr2}$

问题是,您要求它打印一个文本,但您希望它根据您的值进行打印。注意,我认为您必须使用3+风格的python,我在2.7中工作

相关问题 更多 >

    热门问题