簡體   English   中英

為什么 C++ 和 Python 移位運算符結果不同?

[英]Why C++ and Python bitwise shift operator result are diffrernt?

為什么 C++ 和 python 移位運算符的結果不同?
python

>>> 1<<20
1048576

C++

cout <<1<<20;
120

由於 C++ 中的運算符關聯性,結果有所不同。

std::cout << 1 << 20;

是相同的

(std::cout << 1) << 20;

因為operator <<是左關聯的。 你打算做的是

std::cout << (1 << 20);

cout 重載 '<<' 運算符以打印值。 所以當你在做

cout <<1<<20;

它實際上打印 1 和 20 並且不做任何移位

int shifted = 1 << 20;
cout << shifted;

這應該返回與 python 相同的 output

更簡單的方法是

cout << (1 <<20);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM