我有一个简单的问题,我正在学习C编程,我知道!运算符表示逻辑非,我的问题是,在这个例子中,do while循环作为一个条件,它是不是检查变量是否被改变了?
我知道我可能会找到它,但当我试图谷歌'!的它不想显示我的意思。
#include <stdio.h>
int main() {
int input, ok=0;
do {
scanf("%d", &input);
if ( /* condition */) {
//the input is wrong it will scan another one
}
else {
//the input is correct, so the while cycle can stop
//we don't need more inputs
ok = 1;
}
} while (!ok);
//...
//...
//...
return 0;
}
4条答案
按热度按时间jpfvwuh41#
!ok
与ok == 0
相同。记住在C语言中,布尔上下文中的 any 非零标量值表示“true”,而零表示“false”。常见的C语言习惯是用
!foo
代替foo == 0
。它也适用于指针:因此,
while ( x )
与while ( x != 0 )
相同,while ( !x )
与while ( x == 0 )
相同。a9wyjsp72#
不严格地说,给定的代码重复执行循环的内容“while NOT ok”,意思是“while OK为零”。在
else
块中,ok
设置为1,意思是循环不再重复。更正式地说,
!ok
是一个表达式,当ok
等于0时为真,当ok
是除0之外的任何值时为假。m1m5dgzv3#
在逻辑运算的上下文中,除了零()之外的任何东西都是
true
,零是false
。所以
!1
是“!true”是false
!0
为“!false”为true
()任何类型的零:
NULL
计为零,0.0
计为零uemypmqf4#
想想看,ok有一个布尔值,在初始化时是false。
(In c,0的值为false,我假设您知道这一点。)
在do while中,它只是对逻辑值取反,它仍然表示NOT。如果条件为真,它将循环,否则,它将不循环。
如果ok的值为假,你求反它,它就会为真,循环就会,嗯,循环。
我希望你能明白我的意思,它没有别的意思。