为什么即使声明了i的增量,该代码也会无限期地打印10
#include <stdio.h>
int main()
{
int i;
while (i = 10)
{
printf("%d\n",i);
i = i+1;//according to me this will increase the value of i from i = 10 to 11
}
return 0;
}
根据我的预期结果是10,但是只有1次,因为i的值将变为11,并且循环将不执行。
答案 0 :(得分:1)
在while
条件下,每个循环将10分配给i
。
当您进入循环i
等于10时,在循环内部将其增加到11
,然后在循环开始时检查时,再次为其分配10。
如果要停止循环,则需要:
int i = 10;
while (i == 10){ // see the double equal
printf("%d\n",i);
i = i + 1;
}
通过在=
条件中使用单个while
,您将陷入无限循环,因为i = 10
的结果为10,并且每个非0的数字都被视为true
您现在拥有的是:
i put 10 inside of i and say 10 out loud
did i say 0? no so enter the loop
i add 1 to i so now it's 11
i go back to the start
i discard 11, put 10 inside of i and say 10 out loud
did i say 0? no so enter the loop
无限循环
答案 1 :(得分:0)
=
将10
的值赋予i
并返回10
,该值非零,因此被解释为true。如果要检查相等性,请使用==
。现在,编译器将显示错误,因为您使用的是未初始化的i
。您可以通过将i初始化为10
或任何其他值来解决它。
答案 2 :(得分:0)
#include <stdio.h>
int main()
{
int i = 10; // You MUST initialize your variables
while (i == 10) // Use comparison (==) instead of assignment (=)
{
printf("%d\n",i); // Print out "10"
i = i+1; // Increase the value of i from = 10 to 11
}
return 0;
}
答案 3 :(得分:0)
您的问题既是(可能的)错字,也可能是对while
循环工作方式的误解。
while (i = 10)
括号内的代码 分配 将10
的值分配给i
而不是 比较 10
与i
。此外,在C
中,诸如i = 10
的表达式也具有 value -在这种情况下, expression 将是10
,当用作in a
10 loop will evaluate to "true" (any non-zero integral value evaluates to "true" - only zero gives "false") so your loop runs forever: each time the 'control' is evaluated, it will re-assign
i`时的“控制变量” to
时,会给出“ true”答案。
假设此 是一个错字,而您的意思是while (i == 10)
(此处,请正确检查i
是否为10
),那么您几乎可以肯定仍然无法使用您的代码,因为您没有给i
设置初始值。可能这次,循环将 从不 运行,但这是 未定义的行为 -i
绝对没有任何价值。
您需要在声明i
时将其初始化为一个值:
int i = 10;
,或者也许更好,将您的while
循环更改为for
循环:
for (i = 10; i == 10; i++) /// The last bit will make your `i = i+1` line uncessary
随时要求进一步的澄清和/或解释。
答案 4 :(得分:0)
我很确定锻炼的意图:
#include <stdio.h>
int main()
{
int i= 0;
while (i < 10)
{
printf("%d\n",i);
i = i+1;
}
return 0;
}