是否可以将C中的while循环中的数组大小递减大于x--
。例如,你可以在每次迭代时将数组的大小减少三分之一吗?递减c while循环
int n = 10;
while (n < 0)
// do something
(round(n/3))-- // this doesn't work, but can this idea be expressed in C?
谢谢你的帮助!
是否可以将C中的while循环中的数组大小递减大于x--
。例如,你可以在每次迭代时将数组的大小减少三分之一吗?递减c while循环
int n = 10;
while (n < 0)
// do something
(round(n/3))-- // this doesn't work, but can this idea be expressed in C?
谢谢你的帮助!
您可以使用任意表达式:
int n = 10;
while (n > 0) // Note change compared with original!
{
// Do something
n = round(n/3.0) - 1; // Note assignment and floating point
}
注意,您可以仅减少变量,而不是表达式。
你也可以使用一个for
循环:
for (int n = 10; n > 0; n = round(n/3.0) - 1)
{
// Do something
}
在这种情况下,值的序列n
将是相同的(n = 10, 2
)您是否全面使用浮点或没有,所以你可以写:
n = n/3 - 1;
你会看到相同的结果。对于其他上限,序列会改变(n = 11, 3
)。这两种技术都很好,但你需要确保你知道你想要什么,就这些。
代码中没有数组。如果你不想在每次迭代中获得其三分之一的价值,那么你可以做n /= 3;
。请注意,由于n
是积分,因此应用积分除法。
是的,可以向您的变量n
加上或减去任何数字。
通常情况下,如果你想做一些可预测的次数,你可以使用for
循环;当你不确定会发生多少次,而是你正在测试某种状况时,你可以使用一个while
循环。
最稀有的回路是do
/while
循环,当你想在第一时间将while
检查时之前执行循环一次肯定时才使用。
例子:
// do something ten times
for (i = 0; i < 10; ++i)
do_something();
// do something as long as user holds down button
while (button_is_pressed())
do_something();
// play a game, then find out if user wants to play again
do
{
char answer;
play_game();
printf("Do you want to play again? Answer 'y' to play again, anything else to exit. ");
answer = getchar();
} while (answer == 'y' || answer == 'Y');
就像K-说假面舞会中有你的示例代码没有数组,但这里是一个整型数组的例子。
int n = 10;
int array[10];
int result;
// Fill up the array with some values
for (i=0;i<n;i++)
array[i] = i+n;
while(n > 0)
{
// Do something with array
n -= sizeof(array)/3;
}
但是,在给while循环检查n是否小于零的示例代码时要小心。当n初始化为10时,while循环将永远不会执行。在我的例子中,我改变了它。
你是指什么*减量数组* *? – Pubby
这是功课吗? –