c中的while循环递减
是否可以在 C 中的 while 循环中将数组大小减少超过 x--
.例如,您可以在每次迭代时将数组减少数组大小的三分之一吗?
int n = 10;
while (n < 0)
// do something
(round(n/3))-- // this doesn't work, but can this idea be expressed in C?
谢谢您的帮助!
Is it possible to decrement the array size in a while loop in C by more than x--
. For example, can you decrement an array by a third of the array size with each iteration?
int n = 10;
while (n < 0)
// do something
(round(n/3))-- // this doesn't work, but can this idea be expressed in C?
Thank you for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用任何表达式:
请注意,您只能递减变量,而不能递减表达式。
您还可以使用
for
循环:在这种情况下,
n
的值序列将相同 (n = 10, 2
)无论您是否使用浮点进行舍入,因此您都可以编写:并且您会看到相同的结果。对于其他上限,序列将发生变化 (
n = 11, 3
)。两种技术都很好,但是您需要确保您知道自己想要什么,仅此而已。You can use any expression:
Note that you can only decrement variables, not expressions.
You could also use a
for
loop:In this case, the sequence of values for
n
will be the same (n = 10, 2
) whether you round using floating point or not, so you could write:and you'd see the same results. For other upper limits, the sequence would change (
n = 11, 3
). Both techniques are fine, but you need to be sure you know what you want, that's all.是的,可以向变量
n
添加或减去任何数字。通常,如果您想要以非常可预测的次数执行某件事,则可以使用
for
循环;当您不确定某件事会发生多少次,而是测试某种条件时,您可以使用while
循环。最罕见的循环是
do
/while
循环,仅当您想在第一次while
之前执行一次循环时才使用它代码>检查发生。示例:
Yes, it is possible to add or subtract any number to your variable
n
.Usually, if you want to do something a very predictable number of times, you would use a
for
loop; when you aren't sure how many times something will happen, but rather you are testing some sort of condition, you use awhile
loop.The rarest loop is a
do
/while
loop, which is only used when you want to execute a loop one time for certain before the first time thewhile
check occurs.Examples:
您的代码中没有数组。如果您不希望
n
在每次迭代中获得其值的三分之一,则可以执行n /= 3;
。请注意,由于n
是整数,因此将应用积分除法。There is no array in your code. If you wan't
n
to have a third of its value on each iteration, you can don /= 3;
. Note that sincen
is integral then the integral division is applied.正如 K-Ballo 所说,示例代码中没有数组,但这里有一个带有整数数组的示例。
但要小心,在您给出的示例代码中,while 循环正在检查 n 是否小于零。由于 n 被初始化为 10,因此 while 循环将永远不会被执行。我在我的例子中改变了它。
Just like K-Ballo said there is no array in your example code but here is an example with an integer array.
But be careful in the example code you gave the while loop is checking if n is less than zero. As n is intialised to 10 the while loop will never be executed. I have changed it in my example.