欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python-求一元二次方程ax^2+bx+c=0的两个解

程序员文章站 2022-04-06 13:03:36
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net#!/usr/bin/env python3# -*- coding: utf-8 -*-import mathA = float(input('a = '))B = float(input('b = '))C = float(input('c = '))def quadratic(a, b, c): for i in (a, b...

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import math

A = float(input('a = '))
B = float(input('b = '))
C = float(input('c = '))


def quadratic(a, b, c):
    for i in (a, b, c):
        if not isinstance(i, (int, float)):
            raise TypeError("Wrong argument type!")
    if a == 0:
        if b != 0:
            x = -c / b
            return x
        else:
            return "No solution!"
    else:
        delta = b * b - 4 * a * c
        if delta >= 0:
            x1 = (-b + math.sqrt(delta)) / (2 * a)
            x2 = (-b - math.sqrt(delta)) / (2 * a)
            if x1 == x2:
                return x1
            else:
                return x1, x2
        else:
            return "No solution!"


print(quadratic(A, B, C))

# Test
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))

if quadratic(2, 3, 1) != (-0.5, -1.0):
    print('Test FAIL!')
elif quadratic(1, 3, -4) != (1.0, -4.0):
    print('Test FAIL!')
else:
    print('Test PASS~')

 

本文地址:https://blog.csdn.net/chimomo/article/details/109852853

相关标签: Python 函数