孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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:    #float_info.epsilon为接近0值的浮点数,因计算机浮点数只能无限接近0
    print("zero is not allowed")
    x = None
  except ValueError as err:
   print(err)
 return x
 
print("ax2 + bx +c = 0")
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))
 print(x1)
else:
 if discriminant > 0: 
  root = math.sqrt(discriminant)
 else:
  root = cmath.sqrt(discriminant)   #cmath为复数形式
 x1 = (-b+root)/(2*a)
 x2 = (-b-root)/(2*a)
 print(x1)
 print(x2)

posted on 2011-07-10 11:38  孤独的猫  阅读(630)  评论(0编辑  收藏  举报