我知道 OR 是布尔操作数的运算符。但是当我将它与数字一起使用时,我会得到令人惊讶和意想不到的结果,而不是错误。例如:
program test;
uses crt;
begin
clrscr;
writeln(1 or 2);
writeln(2 or 14);
readln;
end.
输出
3
14
我不明白为什么 1 OR 2 等于 3,为什么 2 OR 14 等于 14 ......请有人解释一下。
回答1
它的作用是按位或:
bit 8 7 6 5 4 3 2 1
value 128 64 32 16 8 4 2 1
writeln(1 或 2);
#1: 0 0 0 0 0 0 0 1 = decimal 1
#2: 0 0 0 0 0 0 1 0 = decimal 2
result: 0 0 0 0 0 0 1 1 = decimal 3 = (decimal 1 + decimal 2)
writeln(2 或 14);
#1 0 0 0 0 0 0 1 0 = dec 2
#2 0 0 0 0 1 1 1 0 = dec 14 = (decimal 2 + decimal 4 + decimal 8)
result: 0 0 0 0 1 1 1 0 = dec 14
each bit of #1 OR #2