我是Python的初学者,正在尝试制作二次方公式计算器(似乎是最简单的方法)。我有两个问题。首先,当我询问用户是否要输入另一个方程式时,我调用main(),但是它只是重复先前的输入。我认为这是因为我将系数定义为global(?)变量,但是由于它们不在main()函数中,因此不再要求它们了吗?如何使程序每次都要求用户输入系数?我的另一个问题是如何根据函数定义np.linspace?例如,如果我输入y = x ^ 2-16,则它将窗口移至仅显示y>-16(如果有任何意义)。
再一次,我真的很新,我一直在通过文档+ google找出问题,所以如果我错过了一些非常基本但重要的概念,请告诉我!抱歉,这是一个愚蠢的问题,或者格式/书写不正确。
#quadratic formula calculator
import math
import matplotlib.pyplot as pyplot
import numpy as np
from fractions import Fraction
a = float(Fraction(input("please insert coefficient a: ")))
b = float(Fraction(input("please insert coefficicent b: ")))
c = float(Fraction(input("please insert constant c: ")))
def main():
#calculate discriminant
d = float(b*b) - (4*a*c)
#calculate vertex
Vx = -b/(2*a)
Vy = a*Vx**+b*Vx+c
print("vertex @", Vx, Vy)
#calculate roots
if d < 0:
print("no real roots!")
else:
x1 = (-b + math.sqrt(d))/(2*a)
x2 = (-b - math.sqrt(d))/(2*a)
print("the root(s) are:", x1, x2,)
graphEq()
#check if there are one or two roots
if d == 0:
print("one root!")
if d > 0:
print("two roots!")
def graphEq():
#setup graph
x = np.linspace(-100, 100, 1000)
y = a*x**2 + b*x + c
pyplot.plot(x,y);
pyplot.grid()
pyplot.show()
again = str(input("would you like to graph another eq'n?: yes or no" ))
if again == "yes":
main()
else:
break
if __name__ == '__main__':
main()