-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathqr.py
More file actions
77 lines (65 loc) · 2.22 KB
/
qr.py
File metadata and controls
77 lines (65 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
import math
def get_coef(index, prompt):
'''
Читаем коэффициент из командной строки или вводим с клавиатуры
Args:
index (int): Номер параметра в командной строке
prompt (str): Приглашение для ввода коэффицента
Returns:
float: Коэффициент квадратного уравнения
'''
try:
# Пробуем прочитать коэффициент из командной строки
coef_str = sys.argv[index]
except:
# Вводим с клавиатуры
print(prompt)
coef_str = input()
# Переводим строку в действительное число
coef = float(coef_str)
return coef
def get_roots(a, b, c):
'''
Вычисление корней квадратного уравнения
Args:
a (float): коэффициент А
b (float): коэффициент B
c (float): коэффициент C
Returns:
list[float]: Список корней
'''
result = []
D = b*b - 4*a*c
if D == 0.0:
root = -b / (2.0*a)
result.append(root)
elif D > 0.0:
sqD = math.sqrt(D)
root1 = (-b + sqD) / (2.0*a)
root2 = (-b - sqD) / (2.0*a)
result.append(root1)
result.append(root2)
return result
def main():
'''
Основная функция
'''
a = get_coef(1, 'Введите коэффициент А:')
b = get_coef(2, 'Введите коэффициент B:')
c = get_coef(3, 'Введите коэффициент C:')
# Вычисление корней
roots = get_roots(a,b,c)
# Вывод корней
len_roots = len(roots)
if len_roots == 0:
print('Нет корней')
elif len_roots == 1:
print('Один корень: {}'.format(roots[0]))
elif len_roots == 2:
print('Два корня: {} и {}'.format(roots[0], roots[1]))
# Если сценарий запущен из командной строки
if __name__ == "__main__":
main()
# Пример запуска
# qr.py 1 0 -4