C 编程同时
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x=0;
int y=0;
while (x<15)y++,x+=++y;
printf ("%i %i",x, y);
getchar ();
getchar ();
return 0;
}
我不知道为什么最后x是20而y是8。 请一步步解释。
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x=0;
int y=0;
while (x<15)y++,x+=++y;
printf ("%i %i",x, y);
getchar ();
getchar ();
return 0;
}
I don't know why x is 20 and y is 8 at the end.
Please explain it step by step.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
=>
=>
因此:
请注意,这些值也有一个简单的封闭公式:
x = n*n - n
和y = 2*n
。=>
=>
So:
Note that there is a simple closed formula for these values as well:
x = n*n - n
andy = 2*n
.请记住:
这给出了 x 和 y 的以下值:
Remember that :
Which gives the following values for x and y :
x<15-> y=1,x=0+(y=2)=2
2 15 → y=3,x=2+(y=4)=6
6 15 → y=5,x=6+(y=6)=12
12 15 → y=7, x=12+(y=8)=20
完成
x=20, y=8
逗号运算符强制执行顺序。 x,y表示先执行x,然后执行y。
x<15 -> y=1, x=0+(y=2)=2
2<15 -> y=3, x=2+(y=4)=6
6<15 -> y=5, x=6+(y=6)=12
12<15 -> y=7, x=12+(y=8)=20
Done
x=20, y=8
The comma operator enforces the order of execution. x,y means that x is executed first, and then y.
如果您遵循变量将会发生的情况:
while 循环将退出。
If you follow what is going to happen to your variables :
And while loop will exit.
我把它改成了
现在就可以了
。
为什么?因为
y
在每一步中都会增加两次,并且x
会添加新值。所以你基本上得到 2+4+6+8 = 20。但我不确定这是定义的行为。如果,
运算符定义了一个序列点。I changed it to
and it yields
now.
Why? Because
y
gets incremented twice in each step, andx
gets added the new value. So you essentially get 2+4+6+8 = 20.But I'm not sure it is defined behaviour. It is if the,
operator defines a sequence point.让我们看一下循环(循环后的条件):
在每个循环中,有效完成的是:
这会导致上面写的状态。
Let's go through the loops (conditions after the loop):
In each loop, what effectively is done is:
which results in the states written above.
好吧,这就是 while 子句中每个循环发生的情况:
停止循环现在用数字表示,就在循环结束之前:
Alright, this is what is happening every loop in your while clause:
Now in numbers, right before the end of the loop:
在每次迭代中
in every iteration