[英]Compound conditions using while loop in C.
当amt为0时,程序将忽略停止,直到输入10个数字为止。 输入10个数字后,程序也不会停止。 我的错误在哪里?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
您的测试在分配amt
之前进行。 因此其结果是不确定的。 该测试应移至迭代的末尾,即do/while
。 尽管您可以将amt
分配给一些非零值,但这对我来说有点不整洁。
而且,您确定要使用逻辑与而不是逻辑或吗? 如果两个amt
都不为零且i<10
则只想继续迭代。
当然,如果您确实将测试移到迭代的末尾,那么您将不得不考虑到i
在循环内递增的事实。
为了在10个数字或amt = 0(无论哪个先满足)后停止,您必须将循环条件更改为while (amt!=0 && i < 10)
int amt;
由于您不初始化它。 它具有一些随机值,这会导致程序中出现未定义行为。
您应该始终使用值初始化局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.