>>右移运算符

>>是右移运算符


假设x=5,那么x的二进制为0101,x>>1表示x右移1位,即把最右边一位的1删掉,变为010,此时x=2;
仍然设x=5,二进制0101,x>>2表示x右移2位,把最右边两位的01去掉,变为01,此时x=1。
x>>=1等价于x=x>>1,跟x+=1等价于x=x+1是一个道理

PS: x >>= 1 相当于 x = x / 2;

C++示例:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n;
    while (cin >> n && n)
    {
        cout << n << endl;
        while (n)
        {
            cout << n << " / 2 = ";
            n = n >> 1; // n >>= 1;
            cout << n << endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41705423/article/details/81807376