带有计数变量的循环 - 试图找出结束的地方
我应该输入程序输出。输入是 6, 3
target = int(input())
n = int(input())
while n <= target:
print(n * 2)
n += 1
My output - 6
我的推理 - 3 < 6 这样代码就会运行完毕。 3 * 2 = 6 因此 6 被打印出来。然后我们执行 6 += 1,这将是 7。7 不 <= 6,因此代码不应再次运行。
The expected output:
6
8
10
12
n += 1 是 n = n + 1 的简写。当 n 大于目标时循环结束。
有人可以告诉我哪里出了问题吗?
I'm supposed to type the programs output. Input is 6, 3
target = int(input())
n = int(input())
while n <= target:
print(n * 2)
n += 1
My output - 6
My reasoning- 3 < 6 so the code will run through. 3 * 2 = 6 so 6 gets printed out. Then we do 6 += 1 which would be 7. 7 is not <= 6 so code shouldn't run through again.
The expected output:
6
8
10
12
n += 1 is shorthand for n = n + 1. The loop ends when n is greater than target.
Can someone please tell me where I am going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
print(n * 2)
不会影响n
的值。由于我们没有将n * 2
放入n
的值中,因此n
的值仅改变n += 1< /代码>。
print(n * 2)
does not affect the value ofn
. Since we did not putn * 2
in the value ofn
, the value ofn
changes only byn += 1
.这是
print
和return
语句之间的主要区别。使用 return 改变程序的流程。使用 print 不会
参见此处
This is the main difference between
print
andreturn
statement.Using return changes the flow of the program. Using print does not
See here
自从你去年发布问题以来,这可能有点晚了,但昨晚我被同样的问题困扰了几个小时,无法自己解决。所以,我用谷歌搜索了它,你的问题(而不是任何地方的答案)出现在这里。所以我继续工作。最后,我在几分钟前想出来了,我将在这里写下我的解决方案:
我用第二个输入 n=3 开始该过程,并且由于 n<; 6、经过第一个循环:3 * 2 =6
然后我必须增加我的“n”,但在它达到我的目标 6 之前停止:
(3*2)=6
((3+1)*2)=8
(((3+1)+1)*2)=10 请注意,我增加的 n(括号内)是 5,但仍然小于 6,所以我继续
((((3+1)+1)+1)) *2)= 12 这是我必须停止的时候,因为我增加的 n 已经达到了目标 6 <=6
所以我的回应是:
6
8
10
12
this might be a little late since you posted your question last year, but I was stuck with the same problem last night for hours and could not figure it out on my own. So, I googled it and your question (and not an answer anywhere) popped up here. So I kept working. Finally, I figured it out a few minutes ago and I am going to write my solution here:
I start the process with my second input n=3 and since n< 6, it goes through the first loop: 3 * 2 =6
then I have to increment my 'n' but stop before it reaches my target which is 6:
(3*2)=6
((3+1)*2)=8
(((3+1)+1)*2)=10 note that my incremented n (inside parentheses) is 5 and still less than 6 so I keep going
((((3+1)+1)+1))*2)= 12 here is when I have to stop because my incremented n has reached the target that is 6 <=6
so my response will be:
6
8
10
12