Discuss / Python / 交作业

交作业

Topic source

回风哥哥

#1 Created at ... [Delete] [Delete and Lock User]

具体的quadratic方法只返回具体的值,无 print 语句,具体的调用有测试用例,第三部分的完整文件放到一个 .py 文件里通过 python3 yourfilename.py的方式运行即可测试.

感谢百度百科:http://baike.baidu.com/view/397767.htm 让我重温了下当年学过的内容.

quadratic方法

def quadratic(a, b, c):

    import math

    delta = b*b - 4*a*c

    if a == 0:
        x=(-c)/b
        return x

    elif delta == 0:
        x=(-b)/(2*a)
        return x

    elif delta > 0:
        x1 = (-b+math.sqrt(delta))/(2*a)
        x2 = (-b-math.sqrt(delta))/(2*a)
        return x1, x2

    else:
        return None

测试

# Test

print('------------------------------------------------')

print('Let\'s get the root of this equation: "ax^2 + bx + c = 0"')

a = int(input('Input number for \'a\':'))
b = int(input('Input number for \'b\':'))
c = int(input('Input number for \'c\':'))

print('------------------------------------------------')

quadraticTest = quadratic(a, b, c)

if (quadraticTest != None):
  #print('The equation\'s root:\n => %s, %s' % (quadraticTest[0], quadraticTest[1]))
  print('The equation\'s root:')
  print(quadraticTest)
else:
  print('No solution.')

整个文件内容

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

# function: ax^2 + bx + c = 0
# Formula:
# delta = b^2 - 4*a*c
# if deltar >= 0:
# x1 = (-b + math.sqrt(delta))/(2*a)
# x2 = (-b - math.sqrt(delta))/(2*a)

# description:If you give me 3 arg,I'll give you my result by sqrt!
def quadratic(a, b, c):

    import math

    delta = b*b - 4*a*c

    if a == 0:
        x=(-c)/b
        return x

    elif delta == 0:
        x=(-b)/(2*a)
        return x

    elif delta > 0:
        x1 = (-b+math.sqrt(delta))/(2*a)
        x2 = (-b-math.sqrt(delta))/(2*a)
        return x1, x2

    else:
        return None


# Test

print('------------------------------------------------')

print('Let\'s get the root of this equation: "ax^2 + bx + c = 0"')

a = int(input('Input number for \'a\':'))
b = int(input('Input number for \'b\':'))
c = int(input('Input number for \'c\':'))

print('------------------------------------------------')

quadraticTest = quadratic(a, b, c)

if (quadraticTest != None):
  #print('The equation\'s root:\n => %s, %s' % (quadraticTest[0], quadraticTest[1]))
  print('The equation\'s root:')
  print(quadraticTest)
else:
  print('No solution.')

  • 1

Reply