Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我读到左移e1<<e2相当于e1* 2e2. 但是对于代码:
e1<<e2
e1* 2e2
x=5; printf("%d",x<<3);
输出是40但根据我应该是30。因为x<<4它是80 .(但预计是40)。
x<<4
虽然 forx<<1和x<<2output 是10和20符合预期。
x<<1
x<<2
请解释一下这个逻辑。
00000101 = 4 + 1 = 5
00101000 = 32 + 8 = 40
左移不是连续乘以 2、4、6、8(即 x*2),而是连续乘以 2、4、8、16(即 x^2)。
不,40是完全正确的......
您似乎期待的是:“x * 2 * n”,但左移是不同的操作。
您可以将左移视为有效的“x * 2^n”,其中 n 是数字 - 在您的情况下为 3。所以您正在做的是 5 * 8,即40。
80 也是如此:5 * 16,即 80。