如何使 Java 中的 for 循环以 1 以外的增量增加
如果你有一个像这样的 for 循环:
for(j = 0; j<=90; j++){}
它工作正常。但是当你有一个像这样的for循环时:
for(j = 0; j<=90; j+3){}
它不起作用。有人可以向我解释一下吗?
如果你有一个像这样的 for 循环:
for(j = 0; j<=90; j++){}
它工作正常。但是当你有一个像这样的for循环时:
for(j = 0; j<=90; j+3){}
它不起作用。有人可以向我解释一下吗?
这是因为 不会更改 的值。您需要将其替换为 或使 的值增加 3:j+3
j
j = j + 3
j += 3
j
for (j = 0; j <= 90; j += 3) { }
由于没有其他人真正解决过,我相信我会:Could someone please explain this to me?
j++
是速记,这不是一个实际的操作(好吧,它真的是,但请耐心等待我的解释)
j++
实际上等于操作,除了它不是宏或执行内联替换的东西。这里有很多关于操作以及这意味着什么的讨论(因为它可以被定义为ORj = j + 1;
i+++++i
i++ + ++i
(i++)++ + i
这就引出了:与 .它们称为 和 运算符。你能猜到他们为什么这么叫吗?重要的部分是如何在作业中使用它们。例如,你可以做:或者我们现在做一个示例实验:i++
++i
post-increment
pre-increment
j=i++;
j=++i;
// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;
// yes we could have already set the value to 5 before, but I chose not to.
i = 5;
j = i++;
k = ++i;
print(i, j, k);
//pretend this command prints them out nicely
//to the console screen or something, it's an example
i、j 和 k 的值是什么?
我会给你答案,让你解决它;)
i = 7, j = 5, k = 7;
这就是增量前和增量后运算符的强大功能,以及错误使用它们的危险。但这是编写相同操作顺序的另一种方法:
// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;
// yes we could have already set the value to 5 before, but I chose not to.
i = 5;
j = i;
i = i + 1; //post-increment
i = i + 1; //pre-increment
k = i;
print(i, j, k);
//pretend this command prints them out nicely
//to the console screen or something, it's an example
好的,现在我已经向您展示了运算符的工作原理,让我们来看看为什么它不适用于...还记得我之前如何称它为“速记”吗?就是这样,请参阅第二个示例,因为这是编译器在使用命令之前所做的有效操作(它比这更复杂,但这不是第一个解释)。因此,您将看到“扩展速记”具有 AND,这就是您的请求所具有的全部内容。++
j+3
i =
i + 1
这可以追溯到数学。函数被定义为何处或方程式,因此我们称之为...它当然不是一个函数或方程。它至多是一种表达。这就是全部,一个表达。没有赋值的表达式对我们没有任何好处,但它确实占用了CPU时间(假设编译器没有优化它)。f(x) = mx + b
y = mx + b
mx + b
j+3
我希望这能为你澄清一些事情,并给你一些空间来提出新的问题。干杯!