【发布时间】:2019-01-08 20:05:09
【问题描述】:
这里是初级程序员:)) 我正在做一个学校项目,任务是在一个文件中找到五个函数的根。
在我的一个函数中有两个根,而我的代码只能找到一个。似乎第二个while循环被忽略了。我试图只将这段代码放在一个单独的文件中,并且它可以工作 - 但与其他文件一起它不会工作......
请问有没有什么奇怪的地方;)
def b(x: float):
return -x**2+x+6
def bgraf():
xlim(a1, b1)
ylim(-15, 25)
x = linspace(-5, 10, 1000)
y = b(x)
plot(x, y, 'r')
return
funksjoner = [0, 1, 2, 3, 4]
while response not in funksjoner:
i = int(input("choose a function from 0 to 4"))
response = i
if response in funksjoner:
print("you chose function ", int(funksjoner[i]))
a1 = float(input())
b1 = float(input())
z = a1
y = b1
m = a1
n = b1
NP = True
if int(funksjoner[i]) == funksjoner[1]:
while abs(y-z) > 1e-10:
null1 = (z+y)/2
if b(z)*b(null1)>0 and b(y)*b(null1)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1) == 0:
break
elif b(z)*b(null1)>0:
z = null1
else :
y = null1
while abs(n-m) > 1e-10:
null1_2 = (m+n)/2
if b(m)*b(null1_2)>0 and b(n)*b(null1_2)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1_2) == 0:
break
elif b(m)*b(null1_2)>0:
m = null1_2
else :
n = null1_2
if NP :
print('we have a root when x =', round(((z+y)/2), 1))
if null1 != null1_2:
print('and when x =', round(((m+n)/2), 1))
bgraf()
scatter(null1, 0)
if null1 != null1_2:
scatter(null1_2, 0)
看起来 python 忽略了我放在 if 语句下的第二个 while 循环。有没有其他方法可以做到这一点?
感谢您的关注!
【问题讨论】:
-
这太宽泛了。您需要缩小范围并提及您已经尝试过的调试。
-
不确定,但可以尝试在各个部分打印语句,例如在 while 循环之前打印
abs(n-m) -
您还必须提供所有输入。我建议完全跳过 input() 并立即将变量设置为重新创建您想要演示的“错误”的任何内容。
标签: python python-3.x function if-statement while-loop