为什么“for (i = 100; i <= 0; --i)”永远循环?
unsigned int i;
for (i = 100; i <= 0; --i)
printf("%d\n",i);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
unsigned int i;
for (i = 100; i <= 0; --i)
printf("%d\n",i);
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(9)
也许<= 0?因为从一开始它就是
false
For 循环
将测试更改为
i >; 0
(100 次)或
i >= 0
(101 次)与声明signed int i;
一起,使其实际上减少到 -1 。无符号 int 将从 0 到 max-int(溢出)。The <= 0 maybe? since it is
false
from the startFor loop
Change the test to
i > 0
(100 times)or
i >= 0
(101 times) together with the declarationsigned int i;
so that it actually decreases down to -1. An unsigned int will go from 0 up to max-int (overflow).如果你希望它打印从 100 到 0 的所有数字,那么你需要
在原始代码中第一次运行循环时,i 是 100。测试“100 <= 0”失败,因此没有显示任何内容。
If you want it to print all numbers from 100 down to 0 then you need
The first time your loop ran in your original code, i was 100. The test '100 <= 0' failed and therefore nothing was showing.
如果你希望它从 100 循环到 0,则在循环的第二个条件中应该是
i >= 0
。正如其他人指出的那样,你需要更改你的定义
i
为有符号整数(只是int
),因为当计数器为 -1 时,它将是其他正数,因为您将其声明为无符号int
。Should be
i >= 0
in the second condition in the loop if you want it to loop from 100 to 0.That, and as others have pointed out, you'll need to change your definition of
i
to a signed integer (justint
) because when the counter is meant to be -1, it will be some other positive number because you declared it anunsigned int
.由于
i
是无符号的,因此它永远不会小于零。删除未签名
。另外,将<=
替换为>=
。Since
i
is unsigned, it will never be less than zero. Dropunsigned
. Also, swap the<=
for>=
.由于
i
是无符号的,因此表达式i <= 0
是可疑的,并且等价于i == 0
。并且代码不会打印任何内容,因为条件
i <= 0
在第一次计算时为 false。Since
i
is unsigned, the expressioni <= 0
is suspicious and equivalent toi == 0
.And the code won't print anything, since the condition
i <= 0
is false on its very first evaluation.如果代码不执行任何操作,那么它就没有问题。
假设您希望它打印循环索引
i
从100到1,您需要将i <= 0
更改为i > 0 。
因为它是一个无符号整数,所以不能使用
i >= 0
因为这会导致它无限循环。If the code is supposed to do nothing, nothing is wrong with it.
Assuming that you want it to print the loop index
i
from 100 to 1, you need to changei <= 0
toi > 0
.Because it is an unsigned int, you cant use
i >= 0
because that will cause it to infinitely loop.循环检查
i <= 0;
i
永远不会小于或等于零。其初始值为100。The loop checks for
i <= 0;
i
is never less-than-or-equal to zero. Its initial value is 100.从技术上讲,该代码没有任何问题。 i <= 0 的测试很奇怪,因为 i 是无符号的,但它在技术上是有效的,当 i 为 0 时为 true,否则为 false。在你的情况下,我永远不会碰巧是0。
Technically nothing is wrong with that code. The test for i <= 0 is strange since i is unsigned, but it's technically valid, true when i is 0 and false otherwise. In your case i never happens to be 0.
我怀疑你的意思是测试是
i > 0 。
I suspect you meant the test to be
i > 0
.