为什么delphi在while do循环中执行整数的数学“非”而不是强制转换为 bool 值? 示例
var myint:integer;
...
myint:=1;
while not myint=5 do
begin
myint:=myint+1;
showmessage('myint now is : '+inttostr(myint));
end;
最佳答案
您的表达式使用两个运算符:not
和=
。为了了解它是如何解析的,您需要查阅 operator precedence 的表格。 。
Operators Precedence ---------------------------- @ first (highest) not ---------------------------- * second / div mod and shl shr as ---------------------------- + third - or xor ---------------------------- = fourth (lowest) <> < > <= >= in is ----------------------------
This shows that not
has the highest precedence of all operators, and is of higher precedence than =
. Which means that your expression is parsed as if it were:
(not myint) = 5
在此表达式中,因为它绑定(bind)到整型变量,not
是双向否定。
为了获得您想要的结果,您必须使用括号来表明您希望在 not
之前执行相等测试。 :
not (myint = 5)
现在,在这个表达式中,(myint = 5)
是一个逻辑表达式,因此 not
运算符现在是逻辑否定。
这种性质的问题的答案总是可以在 operator precedence 的表中找到。熟悉这张表将会带来好处。该表将告诉您如何解析省略括号的任何表达式。
最后,正如 Rudy 指出的那样,使用 <>
可以最清晰地编写您的具体表达式。运算符:
myint <> 5
关于delphi - 整数的数学 'not',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293371/