我最近开始学习 C,我觉得这是一个不太聪明的问题,但我想知道你是否可以取 2 个变量,初始化它们,评估它们的条件并在 1 个 for 循环中递增它们
假设我有 2 个整数:a 和 b,我想初始化它们并递增它们。
for(a=1, b= 1; a < 10 , b < 6; a++, b++)
{
printf("a= %d\n", a);
printf("/tb= %d\n", b);
}
有没有这行不通的原因? 还是我做错了?
我看过this question但在其中他/她只想增加 2 个变量,而我想为我的两个变量应用所有内容
最佳答案
Is there a reason this doesnt work? or am I just doing it wrong?
它确实有效,但不是您预期的那样:
a < 10 , b < 6
评估 a < 10
然后 b < 6
但这是 b < 6
的结果被退回。所以你的循环只会转到 5。
让我解释一下 for 循环的工作原理:
您有三个“段”,它们都是可选的:
-
initialisation
这部分在循环开始之前运行一次。 -
condition
如果此condition
在每次迭代之前 评估此部分计算结果为 false 循环退出。 -
increment
在每次 迭代后执行。
for ( initialisation ; condition ; increment ) {
/* body of the for loop */
}
您可以使用 while
实现相同的语义循环:
initialisation;
while (condition) {
/* body of the for loop */
increment;
}
例如:
for (;1;)
永远不会退出和for (;0;)
永远不会运行。
要实现所需的行为,您可以执行以下操作:
//1-9, and values of "b" which are 1-5
int a, b;
for (a = 1, b = 1; a <= 9; ++a, (b <= 4 ? ++b : 0)) {
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("\n");
}
但是您最好在 for 循环的内部执行此操作:
int a, b;
// This reads much better
for (a = 1, b = 1; a <= 9; ++a) {
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("\n");
if (b <= 4) {
++b;
}
}
关于c - 2个变量的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49154483/