减少 For 循环?

发布于 2024-12-13 21:54:10 字数 321 浏览 5 评论 0原文

我可以在 xcode 中递增 FOR 循环,但由于某种原因,相反的操作(即递减)不起作用。

当然,这种递增工作得很好:

for (int i=0; i<10; ++i) {
    NSLog(@"i =%d", i);
}

但是,这种递减不会产生任何结果:

for (int i=10; i<0; --i) {
    NSLog(@"i =%d", i);
}

我的语法一定是错误的,但我相信这对于 xcode 中的 Objective C++ 来说是正确的。

I can increment a FOR loop in xcode, but for some reason the reverse, namely decrementing, doesn't work.

This incrementing works fine, of course:

for (int i=0; i<10; ++i) {
    NSLog(@"i =%d", i);
}

But, this decrementing doesn't produce a thing:

for (int i=10; i<0; --i) {
    NSLog(@"i =%d", i);
}

I must have the syntax wrong, but I believe this is correct for Objective C++ in xcode.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

半暖夏伤 2024-12-20 21:54:10

我认为你的意思是 > 而不是 <

for (int i = 10; i > 0; --i) {

如果你希望 i 的值与原始代码中的值相同,除了相反的顺序(即 9, 8 , 7, ..., 1, 0) 那么您还需要更改边界:

for (int i = 9; i >= 0; --i) {

I think you mean > instead of <:

for (int i = 10; i > 0; --i) {

If you want the values of i to be the same as in the original code except in reverse order (i.e. 9, 8, 7, ..., 1, 0) then you also need to change the boundaries:

for (int i = 9; i >= 0; --i) {
煞人兵器 2024-12-20 21:54:10

我只是想添加记住 --i 首先递减,然后检查和 i-- 检查,然后递减。

I just want to add to keep in mind that --i decrements first, then checks and i-- checks, then decrements.

尐籹人 2024-12-20 21:54:10

您正在检查 i < 0 。这在第一次迭代中是错误的,因此循环不会被执行。将其更改为 i > 0 代替。

You are checking i < 0. This is false in the first iteration and thus the loop isn't executed. Change it to i > 0 instead.

才能让你更想念 2024-12-20 21:54:10

您需要条件为 i>0(如果 i 从 10 开始,则 10<0 为 false,因此它永远不会执行循环代码)。

You need the condition to be i>0 (if i starts at 10, then 10<0 is false, so it never executes the loop code).

╰ゝ天使的微笑 2024-12-20 21:54:10

for (int i = 10; --i >= 0;) {

是在 @Mark Byers 答案中表达 for 循环的一种巧妙方式。

for (int i = 10; --i >= 0;) {

is a neat way to express the for loop in @Mark Byers answer.

删除会话 2024-12-20 21:54:10

将终止条件从 i<0 更改为 i>0

Change the termination condition from i<0 to i>0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文