在输入所有必要的值之后,python拒绝执行while循环
我正在为一个类编写代码,在这个类中,我必须创建一个代码,该代码使用二分法在一个区间之间近似一个三次函数的根。我已经写了一个代码,应该在其中执行,但是;输入变量值后,它执行打印命令,然后在while命令之前中断并停止。文本光标进入一个新行,就像我应该在执行while循环()时输入更多信息一样 导入系统 打印('函数的格式应为:Ax^3+Bx^2+Cx+D.) A=浮点(输入(‘A的值是多少?’)) B=浮点(输入(‘B的值是多少?’)) C=浮点(输入(‘C的值是多少?’)) D=浮点(输入(‘D的值是多少?’)) a=浮点(输入('您的区间最小x值的值是多少?')) b=浮点(输入('您的区间最大x值的值是多少?')) g=a>b 区间=(b-a)/2 公差=10**-6 打印(间隔) 如果g: 打印('b必须大于a'),sys.exit() 当间隔>公差时: 迭代=0 p=(a+b)/2 f0p=A*(p**3)+B*(p**2)+C*p+D 如果f0p==0: print('函数的根是',p) 其他: 如果p<0且a>0: b=p 如果p<0且b>0: a=p 如果p>0且a<0: b=p 如果p>0且b<0: a=p 迭代次数+=1 print('根是x=',p',在'迭代'中计算,'迭代')在输入所有必要的值之后,python拒绝执行while循环,python,while-loop,Python,While Loop,我正在为一个类编写代码,在这个类中,我必须创建一个代码,该代码使用二分法在一个区间之间近似一个三次函数的根。我已经写了一个代码,应该在其中执行,但是;输入变量值后,它执行打印命令,然后在while命令之前中断并停止。文本光标进入一个新行,就像我应该在执行while循环()时输入更多信息一样 导入系统 打印('函数的格式应为:Ax^3+Bx^2+Cx+D.) A=浮点(输入(‘A的值是多少?’)) B=浮点(输入(‘B的值是多少?’)) C=浮点(输入(‘C的值是多少?’)) D=浮点(输入(‘D
我尝试过改变缩进,我到处都在寻找while循环为什么会拒绝执行,文本光标会下降到一个新行,好像它需要更多的输入。你的
当执行循环时,它永远不会完成它没有等待额外的输入。您从不修改间隔值,因此while循环条件始终为true,循环只会继续。为什么它永远不会结束?应在间隔小于公差后终止。
import sys
print('The function should be in the format: Ax^3 + Bx^2 + Cx + D. ')
A = float(input(' What is the value of A? '))
B = float(input(' What is the value of B? '))
C = float(input(' What is the value of C? '))
D = float(input(' What is the value of D? '))
a = float(input(' What is the value of the smallest x-value of your interval? '))
b = float(input(' What is the value of the largest x-value of your interval? '))
g = a > b
interval = (b - a) / 2
tolerance = 10 ** -6
print(interval)
if g:
print('b must be larger than a'), sys.exit()
while interval > tolerance:
iteration = 0
p = (a + b) / 2
f0p = A * (p ** 3) + B * (p ** 2) + C * p + D
if f0p == 0:
print('The root of the function is', p)
else:
if p < 0 and a > 0:
b = p
if p < 0 and b > 0:
a = p
if p > 0 and a < 0:
b = p
if p > 0 and b < 0:
a = p
iteration += 1
print('The root is x=', p, ',calculated in', iteration, 'iterations.')