码迷,mamicode.com
首页 > 编程语言 > 详细

Python一日一练03----一元二次方程的计算

时间:2015-01-19 09:20:40      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:python   一日一练   

要求


由用户随意给定一元二次方程系数a、b、c,计算一元二次方程的解

源码


import cmath                                                             #包含复数运算
import math
import sys

def get_float(msg, allow_zero):
    x = None
    while x is None:
        try:
            x = float(input(msg))
            if not allow_zero and abs(x) < sys.float_info.epsilon:       #sys.float_info.epsilon是浮点数0
                print("zero is not allowed")
                x = None
        except ValueError as err:
            print(err)
    return x

print("ax\N{SUPERSCRIPT TWO} + bx + c = 0")                              #\N{name}给指定的Unicode字符
a = get_float("enter a: ", False)
b = get_float("enter b: ", True)
c = get_float("enter c: ", True)

x1 = None
x2 = None
discriminant = (b ** 2) - (4 * a * c)
if discriminant == 0:
    x1 = -(b / (2 * a))
else:
    if discriminant > 0:
        root = math.sqrt(discriminant)
    else: # discriminant < 0
        root = cmath.sqrt(discriminant)
    x1 = (-b + root) / (2 * a)
    x2 = (-b - root) / (2 * a)

equation = ("{0}x\N{SUPERSCRIPT TWO} + {1}x + {2} = 0"
            " \N{RIGHTWARDS ARROW} x = {3}").format(a, b, c, x1)
if x2 is not None:
    equation += " or x = {0}".format(x2)
print(equation)



如果有什么疑问欢迎到我的微信公众号提问~
技术分享


Python一日一练03----一元二次方程的计算

标签:python   一日一练   

原文地址:http://blog.csdn.net/a359680405/article/details/42846605

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!