gpt4 book ai didi

在 C 中使用 while 循环的复合条件。

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:09 25 4
gpt4 key购买 nike

当 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对于一些非零值,这对我来说有点不整洁。

您肯定是想使用逻辑 AND 而不是逻辑 OR?如果 amt 都存在,您只想继续迭代非零且 i<10 .

当然,如果您确实将测试移至迭代末尾,那么您将不得不考虑 i 的事实已在循环内递增。

关于在 C 中使用 while 循环的复合条件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com