gpt4 book ai didi

c - C 语言编程中与 while 循环有关的 True 或 False

转载 作者:行者123 更新时间:2023-11-30 21:28:36 25 4
gpt4 key购买 nike

有人可以解释一下与此 while 循环有关的 C 语言编程中的 true false 吗?

如果 0 为 false Done=0,并且 while (!Done) 假定为 true,并且 did = 1 也为 true,那么 did=1 如何导致循环“中断”或者退出?

    done=0;
while(!done)
{
c=getchar();
switch(c)
{
case '1':
printf("Beverage $8.00\n");
total+= 8;
break;

case '2':
printf("Candy $3.00\n");
total+= 3;
break;

case '3':
printf("Sandwich $5.00\n");
total+= 5;
break;

case '4':
printf("Hot Dog. $2.00\n");
total+= 2;
break;

case '5':
printf("Popcorn $6.00\n");
total+= 6;
break;

case '=':
printf("Your choices are finished.\n");
printf("The total is:$%.2f\n", total);
printf("Please pay the cashier.\n");
done=1;
break;

default:
printf("I don't understand your choice, please try again.\n");
}
}
return (0);
}

最佳答案

欢迎来到 StackOverflow M.B.

C 中的 while 循环在每个循环之前将其中的任何内容评估为 truefalse

在使用 C 语言编程时,您得到的保证之一是只有 0 为假,而其他所有内容均为 true。这意味着 foobar 为 true,64 为 true,-1 为 true,在您的情况下,1是真的。

因此,! 运算符(not 符号)会将所有为 true 的内容更改为 0,并将0 变为 1

因此,你的 while 循环实际上是在说:
“虽然还没有完成”
或“虽然完成但不真实”
或“虽然完成是错误的”
或“完成后为 0”

因此,当您的最后一个 case 语句 '=' 被命中,并且代码 done=1; 运行时,您的代码将在下次出现时退出并检查 while 循环的条件。

关于c - C 语言编程中与 while 循环有关的 True 或 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40335233/

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