python - while 循环没有终止并且程序没有接受下一个输入
问题描述
我想接受下一个输入,但程序只运行一次,while 循环不会终止导致运行时间超出(我在代码中提到了我要终止 while 循环的地方)
k>1 总是并且 elif 条件不会成为一个 infy 循环,而是代码正在执行完美,仅适用于 1 个输入
for _ in range(int(input())):
k=int(input())
b=2
c=0
i=1
while i>0:
if k>=2:
k-=b
b+=3
elif k<0:
b-=3
k+=b
c+=1
else:
c+=1
i=0 {#here i am trying to make i=0 and terminate the while loop and take the next input}
print(c)
解决方案
路径 1
我将向您展示 1 条形成无限循环的路径。
假设您选择k = -1
:
1: while i>0: # i=1
2: elif k<0: # k=-1
3:b-=3 # b was equal to 2, so gonna be -1
4:k+=b # k now will be -2
5: while i>0: # i=1
6: elif k<0: # k=-2
7:b-=3 # b was equal to -1, so gonna be -4
8:k+=b # k now will be -6
继续...
循环永远不会以这种方式结束
路径 2
k
等于 4 :
1: while i>0: # i=1
2: if k>=2: # k=4
3:k-=b # b=2, so k will be 2
4:b+=3 # b will be 5
5: while i>0: # i=1
6: if k>=2: # k=2
7:k-=b # b=5, so k will be -3
8:b+=3 # b will be 8
9: while i>0: # i=1
10:elif k<0: # k = -3
11: b-=3 # b was equal to 8, so will be 5
12:k+=b # k was equal to -3, so will be 2
现在它循环句子5
- > 再次循环无限
如果你不解释,我不能建议你做什么。我只能解释为什么您的解决方案不正确。
推荐阅读
- terraform - Terraform 13,根据另一个值验证变量
- python - 代码一次触发 2 个函数 | 不和谐.py
- flutter - Flutter - 改变印刷机上的文字不透明度
- java - 为什么即使类路径正确,xls 的 poi-4.1.2 也找不到依赖项?
- android - 带小数点的字符串到浮点转换 Kotlin
- c# - 如何检查.net 5 Source Generator中是否为空引用类型
- .net - WcfSvcHost.exe 在哪里?
- xml - XSD 分层密钥结构
- django - Django >= 3.1 和 is_ajax
- javascript - 如何比较具有不同 ROW 位置和索引的两个 JSON